使用 Python 将一组数字转换为日期格式

Conversion of set of numbers into Date Format using Python

我有一个名为 'train' 的数据框,其列 ID 以非常不寻常的方式表示 'date'。例如ID 中的某个条目:

For example, the value of ID 2013043002 represents the date 30/04/2013 
02:00:00

前4位代表年,后2位分别代表月和日。最后两位数字代表时间。

所以我想把它转换成合适的日期时间格式来进行时间序列分析。

使用 datetime 进行日期时间操作。

datetime.strptime(d,"%Y%m%d%H").strftime("%d/%m/%Y %H:%M:%S")

使用to_datetime with parameter format - check http://strftime.org/:

df = pd.DataFrame({'ID':[2013043002,2013043002]})

df['ID'] = pd.to_datetime(df['ID'], format='%Y%m%d%H')
print(df)
                   ID
0 2013-04-30 02:00:00
1 2013-04-30 02:00:00

print(df['ID'].dtype)
datetime64[ns]

首先,如果您要在 Id 中始终使用相同的输入样式,您可以使用字符串或数字格式...

Id = 2013043002 
Year = Id[0:3] 
Month = Id[4:5] 
Day = Id[6:7] 
Time= Id[-2:-1]  

DateFormat = "{}-{}-{}".format(Day,Month,Year)
TimeFormar = "%d:00:00"%Time 
Print (DateFormat) 
Output:
04:30:2013 

然后用这个你可以将它包装成一个函数并通过循环传递每个 ID 并管理你的数据。

当然,如果您不知道您以前的 ID 输入格式,您应该使用其他时间模块选项,并管理字符串格式以按您想要的顺序显示它。

通过使用模块 datetime,您可以使用函数 strptime 轻松做到这一点:

my_date = datetime.datetime.strptime(ID, "%Y%m%d%H")

"%Y%m%d%H" is the format of your date : %Y is the year, %m is the month(0 padded), %d is the day(0 padded) and %H is the hour(24H, 0 padded). See http://strftime.org/ for more.