玩转python datetime

背景介绍

需要把文本数据格式的时间转变为空格划分的时间信息,见下图

功能实现

技术分解

  1. 提取时间信息
  2. 字符串处理,头信息组装
  3. datetime格式转变,运用

技术实现

    import pandas as pd

    import datetime,time
    csvFile=r"C:\Users\yezhaoliang\Desktop\ew.csv"

    csvData=pd.read_csv(csvFile,skiprows=1)

    # print(csvData.iloc[1,0])
    # a=csvData.iloc[1,0]
    # print(a)
    # timeArray = time.strptime(a, "%Y%m%d %H:%M:%S")
    #
    # print(timeArray[1])
    # print(csvDatum)
    versionName='version'
    versionNumber='01'
    sitename='site name'
    measureTimeName='measure period'
    siteposName='site position'
    coorName='coordinate system'
    measureHeightName='measurement height'

    ### 必须填对测风塔位置!
    sitePositionX='20379022.37'
    sitePositionY='4475481.11'
    bakFile = open("./testOutput2.tws", 'w')
  ## 用于字符串的填充!打印效果好看些
    NameListLength=22
    earlistDay=csvData.iloc[0,0]
    earlistDate = datetime.datetime.strptime(earlistDay, '%Y%m%d %H:%M:%S')
    latestDay=csvData.iloc[len(csvData)-1,0]
    latestDate = datetime.datetime.strptime(latestDay, '%Y%m%d %H:%M:%S')
    print(f'{versionName.ljust(NameListLength," ")}: {versionNumber}',file=bakFile)
    print(f'{sitename.ljust(NameListLength," ")}: Tower_wind_{earlistDate.year:04}{earlistDate.month:02}{earlistDate.day:02}'
          f'-{latestDate.year:04}{latestDate.month:02}{latestDate.day:02}.tim',file=bakFile)
    print(f'{measureTimeName.ljust(NameListLength," ")}: {earlistDate:%m/%d/%Y %H:%M}-{latestDate:%m/%d/%Y %H:%m}',file=bakFile)
    print(f'{siteposName.ljust(NameListLength," ")}: {sitePositionX} {sitePositionY}',file=bakFile)
    print(f'{coorName.ljust(NameListLength," ")}: 3',file=bakFile)
    print(f'{measureHeightName.ljust(NameListLength," ")}: 90.0',file=bakFile)
    print(f'',file=bakFile)
    print(f'rec nr:\tyear:\tmon:\tdate:\thour:\tmin:\tdir:\tspeed:',file=bakFile)
###正式打入需要的数据
    for i in range(len(csvData)):
        a = csvData.iloc[i, 0]
        direction = csvData.iloc[i, 1]
        velocity = csvData.iloc[i, 2]
        d1 = datetime.datetime.strptime(a, '%Y%m%d %H:%M:%S')
        print(f'{i}\t{d1.year:04}\t{d1.month:02}\t{d1.day:02}\t{d1.hour:02}\t{d1.minute:02}\t{direction}\t{velocity}',file=bakFile)
    bakFile.close()

附录

  1. 补全字符串
  2. Python格式化字符串f-string概览
  3. 输出print信息到文件
Related
叶昭良
叶昭良
Engineer of offshore wind turbine technique research

My research interests include distributed energy, wind turbine power generation technique , Computational fluid dynamic and programmable matter.