Python 3.x python-将日期转换为字符串,并在
我的数据框中有一些日期是字符串,如:Python 3.x python-将日期转换为字符串,并在,python-3.x,dataframe,date,Python 3.x,Dataframe,Date,我的数据框中有一些日期是字符串,如: 0 2015-02-09 12:40:59+00 1 2015-02-09 12:44:32+00 2 2015-02-09 12:43:05+00 3 2015-02-09 12:49:11+00 4 2015-02-09 12:52:49+00 ... 1923657 2021-04-08 07:45
0 2015-02-09 12:40:59+00
1 2015-02-09 12:44:32+00
2 2015-02-09 12:43:05+00
3 2015-02-09 12:49:11+00
4 2015-02-09 12:52:49+00
...
1923657 2021-04-08 07:45:32+00
1923658 2021-04-08 05:40:12+00
1923659 2021-04-08 08:44:08+00
1923660 2021-04-08 00:34:37+00
1923661 2021-04-08 04:53:31+00
我将它们转换为ms,如:
col0='startingtimestamp'
df[col0] = df[col0].apply(lambda x: datetime.strptime(x[:19], "%Y-%m-%d %H:%M:%S").timestamp())
这是可行的,但有没有更快、更短的解决方案
请给我一个提示。谢谢
import pandas as pd
只需使用rstrip()
方法、to\u datetime()
方法和total\u seconds()
方法:
df['col0']=df['col0'].astype(str).str.rstrip('+00')
df['col0']=pd.to_datetime(df['col0'])
df['col0']=(df['col0'] - pd.to_datetime('1970-1-1')).dt.total_seconds()