日期表达的转换——python: DOY(day of year) AND (DATE:year-month-day)

将csv中的年月日转换为DOY,其中年月日在CSV中的具体情况如下表所示:

 

 代码如下:

# Ren Yan
import math

import pandas as pd
from pandas import Series
file = pd.read_csv('读入csv')
year_file = file['Year']  # 每一列的名字
month_file = file['Month']
day_file = file['Day']

def date2doy(year, month, day):
    month_leapyear = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]  # 闰年
    month_notleap = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    doy = 0

    if month == 1:
        pass
    elif year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
        for i in range(month - 1):
            doy += month_leapyear[i]
    else:
        for i in range(month - 1):
            doy += month_notleap[i]
    doy += day
    return doy


DOY = []
length = len(year_file) - 2  # 循环次数
for j in range(0, length):
    year_j = math.ceil(year_file[j])  # 将浮点型变为整型
    month_j = math.ceil(month_file[j])
    day_j = math.ceil(day_file[j])
    DOY_j = date2doy(year_j, month_j, day_j)
    year_doy = str(year_j) + str(DOY_j) # 使得输出形式为yeardoy,如:2016255
    DOY.append(year_doy)

DOY = Series(DOY) # 将list变为series,因为只有series才可以作为参数添加到表格中

file['DOY'] = DOY # 在原始的表格中添加新的一列,列名为DOY,数值为先前计算的DOY
file.to_csv(r'F:/paper_graduate/ship-based data/2016doy1.csv', mode='a', index=False) # 输出到新的csv中

如果是将DOY变为year-month-day的形式:

其他的类似,定义新的函数:

def doy2date(year, doy):
    month_leapyear = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]  # 闰年
    month_notleap = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

    if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
        for i in range(0, 12):
            if doy > month_leapyear[i]:
                doy -= month_leapyear[i]  # 用来判断月份
                continue
            if doy <= month_leapyear[i]:
                month = i + 1  
                day = doy  # 某月的第多少天
                break
    else:
        for i in range(0, 12):
            if doy > month_notleap[i]:
                doy -= month_notleap[i]
                continue
            if doy <= month_notleap[i]:
                month = i + 1
                day = doy
                break
    return month, day

转换代码参考: https://blog.csdn.net/weixin_30748995/article/details/101570875

 

posted @ 2022-05-11 20:27  搞研究不秃头  阅读(856)  评论(0)    收藏  举报