无法将日期时间转换为python可读格式

时间:2017-08-21 08:06:22

标签: python datetime

我的日期时间范围如下:

Date
2017-04-02 12:00 AM
2017-04-02 01:00 AM
2017-04-02 02:00 AM
2017-04-02 03:00 AM
2017-04-02 04:00 AM
2017-04-02 05:00 AM
2017-04-02 06:00 AM
2017-04-02 07:00 AM
2017-04-02 08:00 AM
2017-04-02 09:00 AM
2017-04-02 10:00 AM

我想将它们全部转换为python日期时间以在x轴上绘制它。我使用了以下代码:

dates=fire['Date']#copy date value in dataframe
x = dt.datetime.strptime('dates',"%Y-%m-%d %I:%M %p").date() 

但它给我的错误是:

time data 'd' does not match format '%Y-%m-%d %I:%M %p'

如何将所有这些日期转换为python可读日期?

1 个答案:

答案 0 :(得分:3)

d是一个变量,因此您需要删除引号:

x = [dt.datetime.strptime(d,"%Y-%m-%d %I:%M %p").date() for d in dates]

编辑:可重复的示例

遵循OP请求,这是一个可重现的例子:

import pandas as pd 
import datetime as dt 
from StringIO import StringIO 

data="""
Date
2017-04-02 12:00 AM
2017-04-02 01:00 AM
2017-04-02 02:00 AM
2017-04-02 03:00 AM
2017-04-02 04:00 AM
2017-04-02 05:00 AM
2017-04-02 06:00 AM
2017-04-02 07:00 AM
2017-04-02 08:00 AM
2017-04-02 09:00 AM
2017-04-02 10:00 AM
"""
# StringIO is used to simulate reading from a csv file
df = pd.read_csv(StringIO(data))
print(df.head()) 

dates = df['Date']
x = [dt.datetime.strptime(d,"%Y-%m-%d %I:%M %p").date() for d in dates]
print(x) 

输出:

[datetime.date(2017, 4, 2), datetime.date(2017, 4, 2), datetime.date(2017, 4, 2), datetime.date(2017, 4, 2), datetime.date(2017, 4, 2), datetime.date(2017, 4, 2), datetime.date(2017, 4, 2), datetime.date(2017, 4, 2), datetime.date(2017, 4, 2), datetime.date(2017, 4, 2), datetime.date(2017, 4, 2)]

另外,pandas可以按如下方式解析日期:

df2 = pd.read_csv(StringIO(data), parse_dates=['Date'])

输出:

                 Date
0 2017-04-02 00:00:00
1 2017-04-02 01:00:00
2 2017-04-02 02:00:00
3 2017-04-02 03:00:00
4 2017-04-02 04:00:00