[英]Pandas: converting timestamp into datetime
I have a column of date time strings in UTC
which I need to convert to a viable datetime format in EST
using pandas
.我有一列
UTC
日期时间字符串,我需要使用pandas
将其转换为EST
可行的日期EST
格式。 I successfully converted the column, however I feel that my solution is long-winded and can be simplified, but I'm not sure how.我成功转换了该列,但是我觉得我的解决方案冗长且可以简化,但我不确定如何进行。 Here is the way I'm currently converting the dates:
这是我目前转换日期的方式:
df['datetime'] = pd.to_datetime(df['datetime'])
df['datetime'] = df['datetime'].dt.strftime('%m/%d/%Y %H:%M:%S')
df['datetime'] = pd.to_datetime(df['datetime'])
df['datetime'] = df['datetime'] - pd.Timedelta(hours=5)
Here are a few sample of the original string format:以下是原始字符串格式的一些示例:
2014-02-07T00:25:40Z
2014-02-07T00:25:40Z
2014-02-07T00:25:41Z
2014-02-07T00:25:42Z
2014-02-07T00:25:42Z
2014-02-07T00:25:43Z
2014-02-07T00:25:43Z
2014-02-07T00:25:44Z
2014-02-07T00:25:44Z
2014-02-07T00:25:44Z
Can I convert this column with one or two lines?我可以用一行或两行转换此列吗? I tried performing the
Timedelta()
in the same step as the datetime formatting but received an error.我尝试在与日期时间格式相同的步骤中执行
Timedelta()
但收到错误。 Alternately I tried using tz_convert()
and tz_localize()
but received error with tz_convert()
saying that my datetime wasn't a viable datetime format (hence why I reset the column to datetime after formatting).或者,我尝试使用
tz_convert()
和tz_localize()
但收到错误tz_convert()
说我的日期时间不是可行的日期时间格式(因此我为什么在格式化后将列重置为日期时间)。 With tz_localize()
it just added -5:00
to the end of my datetime instead of actually subtracting the 5 hours from the UTC
time.使用
tz_localize()
它只是将-5:00
添加到我的日期时间的末尾,而不是实际从UTC
时间中减去 5 小时。
This is how the output should look:这是输出的外观:
2014-02-06 19:25:40
2014-02-06 19:25:40
2014-02-06 19:25:41
2014-02-06 19:25:42
2014-02-06 19:25:42
2014-02-06 19:25:43
2014-02-06 19:25:43
2014-02-06 19:25:44
2014-02-06 19:25:44
2014-02-06 19:25:44
I will do tz_localize
and tz_localize
我会做
tz_localize
和tz_localize
pd.to_datetime(df.date).dt.tz_localize('UTC').\
dt.tz_convert('EST').\
dt.strftime('%Y-%m-%d %H:%M:%S')
0 2014-02-06 19:25:40
1 2014-02-06 19:25:41
2 2014-02-06 19:25:42
3 2014-02-06 19:25:42
4 2014-02-06 19:25:43
5 2014-02-06 19:25:43
6 2014-02-06 19:25:44
7 2014-02-06 19:25:44
8 2014-02-06 19:25:44
Name: date, dtype: object
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.