首页 > 解决方案 > 如何以不寻常的日期\时间格式阅读

问题描述

我有一个带有日期\时间列的小 df,使用我从未见过的格式。

即使我使用 parse_dates,Pandas 也会将其作为对象读取,并且 to_datetime() 会阻塞它。

列中的日期格式如下:

2019/12/29 GMT+8 18:00
2019/12/15 GMT+8 05:00

我认为最好的方法是使用日期解析模式。像这样的东西:

dateparse = lambda x: pd.datetime.strptime(x, '%Y-%m-%d %H:%M:%S')
df = pd.read_csv(infile, parse_dates=['datetime'], date_parser=dateparse)

但我根本不知道如何处理这种格式。

标签: python-3.xpandasdatetime

解决方案


import pandas as pd

# sample data
df = pd.DataFrame({'datetime': ['2019/12/29 GMT+8 18:00', '2019/12/15 GMT+8 05:00', '2019/12/15 GMT+10 05:00', '2019/12/15 GMT-10 05:00']})

# display(df)
datetime
2019/12/29 GMT+8 18:00
2019/12/15 GMT+8 05:00
2019/12/15 GMT+10 05:00
2019/12/15 GMT-10 05:00

# fix the format
df.datetime = df.datetime.str.split(' ').apply(lambda x: x[0] + x[2] + x[1][3:].zfill(3) + ':00')

# convert to a utc datetime
df.datetime = pd.to_datetime(df.datetime, format='%Y/%m/%d%H:%M%z', utc=True)

# display(df)
datetime
2019-12-29 10:00:00+00:00
2019-12-14 21:00:00+00:00
2019-12-14 19:00:00+00:00
2019-12-15 15:00:00+00:00


print(df.info())
[out]:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 1 columns):
 #   Column    Non-Null Count  Dtype              
---  ------    --------------  -----              
 0   datetime  4 non-null      datetime64[ns, UTC]
dtypes: datetime64[ns, UTC](1)
memory usage: 160.0 bytes

推荐阅读