python-3.x - 如何以不寻常的日期\时间格式阅读
问题描述
我有一个带有日期\时间列的小 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)
但我根本不知道如何处理这种格式。
解决方案
- UTC 的数据时间格式非常适合转换偏移量。
strftime()
和strptime()
格式代码- 格式必须是
+
or-
然后00:00
- 用于
str.zfill
回填0
符号和整数之间的 s+08:00
或-08:00
或+10:00
或-10:00
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
推荐阅读
- xaml - 将 InputTransparent 属性设置为 True 的 ListView 正在影响 ListView 内的按钮
- c++ - 读取 json 文本文件解析失败。ostringstream 对它有什么作用吗?
- sql-server - 如何在 MS SQL 中从年初获取值
- javascript - 使用画布,如何在图像中切割带有嵌入阴影的孔?
- c++ - 运算符 const char* () 和显式复制 ctor
- mysql - 检查 MySQL 中 JSON 数据中是否存在值
- xamarin - Xamarin IOS 或 Xamarin Android 项目能否引用 .NET 5 或 .NET Core 项目
- reactjs - 从函数体而不是 useEffect(fn,[]) 获取数据时有什么缺点或问题?
- gatsby - Gastby 主页组件仅在 Prod 中的所有页面上双重渲染(不在本地/开发中)
- python - 条件语句和多个函数