如何将数据框转换为日期时间格式
How to convert a dataframe into datetime format
我有这个数据框:
3_21_19_59
1
4
22
25
28
31
34
37
.
.
.
.
它有 410 行。
此处3_21_19_59
:3
表示月份,21
表示日期,19
表示小时,59
表示分钟。下面几行中的数字:1
、4
、22
... 是秒。
现在,我想将此数据框转换为这样的日期时间格式:
2020-03-21 19:59:00
2020-03-21 19:59:01
2020-03-21 19:59:04
2020-03-21 19:59:22
2020-03-21 19:59:25
2020-03-21 19:59:28
...
...
...
等等。 60 秒后,分钟应自动递增。例如:如果是 64 秒,它应该像 2020-03-21 19:60:04
。
如有任何帮助,我们将不胜感激。
首先通过 to_datetime
使用格式和 errors='coerce'
参数转换日期时间,因此缺少不匹配值的值。然后转发 fillinf 以重新发送 datetimes
.
然后处理 seconds
- 首先通过 to_numeric
, then to timedeltas by to_timedelta
转换为数字,最后添加到日期时间:
print (df)
col
0 3_21_19_59
1 1
2 4
3 22
4 25
5 28
6 31
7 34
8 37
d = pd.to_datetime('20_' + df['col'], format='%y_%m_%d_%H_%M', errors='coerce').ffill()
td = pd.to_numeric(df['col'], errors='coerce').fillna(0)
df['col'] = d.add(pd.to_timedelta(td, unit='s'))
print (df)
col
0 2020-03-21 19:59:00
1 2020-03-21 19:59:01
2 2020-03-21 19:59:04
3 2020-03-21 19:59:22
4 2020-03-21 19:59:25
5 2020-03-21 19:59:28
6 2020-03-21 19:59:31
7 2020-03-21 19:59:34
8 2020-03-21 19:59:37
我有这个数据框:
3_21_19_59
1
4
22
25
28
31
34
37
.
.
.
.
它有 410 行。
此处3_21_19_59
:3
表示月份,21
表示日期,19
表示小时,59
表示分钟。下面几行中的数字:1
、4
、22
... 是秒。
现在,我想将此数据框转换为这样的日期时间格式:
2020-03-21 19:59:00
2020-03-21 19:59:01
2020-03-21 19:59:04
2020-03-21 19:59:22
2020-03-21 19:59:25
2020-03-21 19:59:28
...
...
...
等等。 60 秒后,分钟应自动递增。例如:如果是 64 秒,它应该像 2020-03-21 19:60:04
。
如有任何帮助,我们将不胜感激。
首先通过 to_datetime
使用格式和 errors='coerce'
参数转换日期时间,因此缺少不匹配值的值。然后转发 fillinf 以重新发送 datetimes
.
然后处理 seconds
- 首先通过 to_numeric
, then to timedeltas by to_timedelta
转换为数字,最后添加到日期时间:
print (df)
col
0 3_21_19_59
1 1
2 4
3 22
4 25
5 28
6 31
7 34
8 37
d = pd.to_datetime('20_' + df['col'], format='%y_%m_%d_%H_%M', errors='coerce').ffill()
td = pd.to_numeric(df['col'], errors='coerce').fillna(0)
df['col'] = d.add(pd.to_timedelta(td, unit='s'))
print (df)
col
0 2020-03-21 19:59:00
1 2020-03-21 19:59:01
2 2020-03-21 19:59:04
3 2020-03-21 19:59:22
4 2020-03-21 19:59:25
5 2020-03-21 19:59:28
6 2020-03-21 19:59:31
7 2020-03-21 19:59:34
8 2020-03-21 19:59:37