我是Python pandas的新手。我有3列如下。日期和时间列应合并到一个名为datetime的列,并转换为UTC时区。此外,在创建datetime列之后,应删除日期和时间列。
date Seq time
1/15/2018 1 0:00
1/15/2018 2 0:01
1/15/2018 3 0:02
1/15/2018 4 0:03
1/15/2018 5 0:04
1/15/2018 6 0:05
1/15/2018 7 0:06
1/15/2018 8 0:07
1/15/2018 9 0:08
1/15/2018 10 0:09
1/15/2018 11 0:10
1/15/2018 12 0:11
1/15/2018 13 0:12
我尝试了以下代码,但我发现日期时间是在纪元时间戳中。
df['datetime'] = df['date'] + " " + df['time'] + ":00"
logging.info(df)
df['datetime'] = pd.to_datetime(df['datetime'])
df['datetime'] = df['datetime'].apply(
lambda x: datetime.strptime(str(x), "%Y-%m-%d %H:%M:%S+00:00"))
有人可以帮忙吗?
答案 0 :(得分:2)
我认为不需要分配给列,只需按dt.tz_localize
加入和转换,最后按drop
删除列:
df['datetime'] = pd.to_datetime(df['date'] + " " + df['time']).dt.tz_localize('UTC')
df = df.drop(['date','time'], axis=1)
print (df)
Seq datetime
0 1 2018-01-15 00:00:00+00:00
1 2 2018-01-15 00:01:00+00:00
2 3 2018-01-15 00:02:00+00:00
3 4 2018-01-15 00:03:00+00:00
4 5 2018-01-15 00:04:00+00:00
5 6 2018-01-15 00:05:00+00:00
6 7 2018-01-15 00:06:00+00:00
7 8 2018-01-15 00:07:00+00:00
8 9 2018-01-15 00:08:00+00:00
9 10 2018-01-15 00:09:00+00:00
10 11 2018-01-15 00:10:00+00:00
11 12 2018-01-15 00:11:00+00:00
12 13 2018-01-15 00:12:00+00:00