[英]Unable to get time difference between to pandas dataframe columns
I have a pandas dataframe that contains a couple of columns.我有一个包含几列的熊猫数据框。 Two of which are start_time and end_time.
其中两个是 start_time 和 end_time。 In those columns the values look like - 2020-01-04 01:38:33 +0000 UTC
在这些列中,值看起来像 - 2020-01-04 01:38:33 +0000 UTC
I am not able to create a datetime object from these strings because I am not able to get the format right -我无法从这些字符串创建日期时间对象,因为我无法正确获取格式 -
df['start_time'] = pd.to_datetime(df['start_time'], format="yyyy-MM-dd HH:mm:ss +0000 UTC")
I also tried using yyyy-MM-dd HH:mm:ss %z UTC
as a format我也尝试使用
yyyy-MM-dd HH:mm:ss %z UTC
作为格式
This gives the error -这给出了错误 -
ValueError: time data '2020-01-04 01:38:33 +0000 UTC' does not match format 'yyyy-MM-dd HH:mm:ss +0000 UTC' (match)
您只需要使用to_datetime
可以识别的正确时间戳格式
df['start_time'] = pd.to_datetime(df['start_time'], format="%Y-%m-%d %H:%M:%S +0000 UTC")
There are some notes below about this problem:关于这个问题有以下几点说明:
1. About your error 1.关于你的错误
This gives the error -
这给出了错误 -
You have parsed a wrong datetime format that will cause the error.您解析了会导致错误的错误日期时间格式。 For correct format check this one https://strftime.org/ .
对于正确的格式,请检查这个https://strftime.org/ 。 Correct format for this problem would be:
"%Y-%m-%d %H:%M:%S %z UTC"
此问题的正确格式是:
"%Y-%m-%d %H:%M:%S %z UTC"
2. Pandas limitation with timezone 2. Pandas 时区限制
Parsing UTC timezone as %z
doesn't working on pd.Series (it only works on index value).将 UTC 时区解析为
%z
不适用于 pd.Series(它仅适用于索引值)。 So if you use this, it will not work :因此,如果您使用它,它将不起作用:
df['startTime'] = pd.to_datetime(df.startTime, format="%Y-%m-%d %H:%M:%S %z UTC", utc=True)
Solution for this is using python built-in library for inferring the datetime data:解决方案是使用 python 内置库来推断日期时间数据:
from datetime import datetime
f = lambda x: datetime.strptime(x, "%Y-%m-%d %H:%M:%S %z UTC")
df['startTime'] = pd.to_datetime(df.startTime.apply(f), utc=True)
@fmarm answer only help you dealing with date and hour data, not UTC timezone. @fmarm 回答只能帮助您处理日期和小时数据,而不是 UTC 时区。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.