微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Pandas datetime - 仅将时间保留为 dtype datetime

如何解决Pandas datetime - 仅将时间保留为 dtype datetime

我想要 Pandas 中没有日期的时间。 我想将时间保留为 dtype datetime64[ns] 而不是对象,以便我可以确定时间之间的时间段。

我得到的最接近的如下,但它返回新列中的日期,而不是 dtype datetime 所需的时间。

df_pres_mf['time'] = pd.to_datetime(df_pres_mf['time'],format ='%H:%M',errors = 'coerce')   # returns date (1900-01-01) and actual time as a dtype datetime64[ns] format

df_pres_mf['just_time'] = df_pres_mf['time'].dt.date
df_pres_mf['normalised_time'] = df_pres_mf['time'].dt.normalize()
df_pres_mf.head()

将日期返回为 1900-01-01,而不是所需的时间。

编辑:数据

               time
1900-01-01 11:16:00
1900-01-01 15:20:00
1900-01-01 09:55:00
1900-01-01 12:01:00

解决方法

根据您的日期格式使用正确的格式并转换为日期时间

df['time'] = pd.to_datetime(df['time'],format='%Y-%m-%d %H:%M:%S')

根据首选格式进行格式化

df['time'].dt.strftime('%H:%M')

输出

0    11:16
1    15:20
2    09:55
3    12:01
Name: time,dtype: object
,

你可以像 Vishnudev 建议的那样做,但是你会有 dtype: object(甚至是字符串,在使用 dt.strftime 之后),你说你不想要。

您要找的东西不存在,但我能得到的最接近的东西是转换为 timedeltas。乍一看这似乎不是一个解决方案,但实际上非常有用。

这样转换:

# sample df
df
>>
                 time
0 2021-02-07 09:22:00
1 2021-05-10 19:45:00
2 2021-01-14 06:53:00
3 2021-05-27 13:42:00
4 2021-01-18 17:28:00

df["timed"] = df.time - df.time.dt.normalize() 
df
>>
 
                 time           timed
0 2021-02-07 09:22:00 0 days 09:22:00  # this is just the time difference
1 2021-05-10 19:45:00 0 days 19:45:00  # since midnight,which is essentially the 
2 2021-01-14 06:53:00 0 days 06:53:00  # same thing as regular time,except
3 2021-05-27 13:42:00 0 days 13:42:00  # that you can go over 24 hours
4 2021-01-18 17:28:00 0 days 17:28:00

这允许您计算时间之间的时间段,如下所示:

# subtract the last time from the current
df["difference"] = df.timed - df.timed.shift() 
df
Out[48]: 
                 time           timed        difference
0 2021-02-07 09:22:00 0 days 09:22:00               NaT
1 2021-05-10 19:45:00 0 days 19:45:00   0 days 10:23:00
2 2021-01-14 06:53:00 0 days 06:53:00 -1 days +11:08:00  # <-- this is because the last
3 2021-05-27 13:42:00 0 days 13:42:00   0 days 06:49:00  # time was later than the current
4 2021-01-18 17:28:00 0 days 17:28:00   0 days 03:46:00  # (see below)

要消除奇怪的差异,请使其绝对化:

df["abs_difference"] = df.difference.abs()
df
>>
                 time           timed        difference  abs_difference
0 2021-02-07 09:22:00 0 days 09:22:00               NaT             NaT
1 2021-05-10 19:45:00 0 days 19:45:00   0 days 10:23:00 0 days 10:23:00
2 2021-01-14 06:53:00 0 days 06:53:00 -1 days +11:08:00 0 days 12:52:00  ### <<--
3 2021-05-27 13:42:00 0 days 13:42:00   0 days 06:49:00 0 days 06:49:00
4 2021-01-18 17:28:00 0 days 17:28:00   0 days 03:46:00 0 days 03:46:00

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。