根据各自的时区转换每一行的日期时间

Convert datetime for each row according to the respective timezone

我正在尝试找出一种方法将一行的日期时间转换为其各自的时区。

例如,第1列是'user name',第2列是Asia/Kolkata时区的'sent_time',第3列是'timezone',记录了用户所在的时区生活。有没有办法将所有 'sent_time' 列值转换为它们各自的时区?

这是数据示例:

用户 ID sent_time app_timezone
12345 1610237077 America/Los_Angeles
25674 1610238621 America/New_York
87940 1610238622 Asia/Kolkata
23420 1610238622 Europe/London

您可以执行以下操作,

import pandas as pd

# dummy data:
# df
#    User Id   sent_time          app_timezone
# 0     12345  1610237077  America/Los_Angeles
# 1     25674  1610238621     America/New_York
# 2     87940  1610238622         Asia/Kolkata
# 3     23420  1610238622        Europe/London

# parse Unix time to datetime, to UTC
df['sent_time'] = pd.to_datetime(df['sent_time'], unit='s', utc=True)

# now we can derive the time in user's tz
df['sent_time_user'] = df.apply(lambda r: r['sent_time'].tz_convert(r['app_timezone']),
                                axis=1)

对于虚拟示例,您现在有

df['sent_time_user']
0    2021-01-09 10:34:37-08:00
1    2021-01-09 14:00:21-05:00
2    2021-01-10 00:30:22+05:30
3    2021-01-09 19:00:22+00:00
Name: sent_time_user, dtype: object

进一步阅读:tz_localize and tz_convert。另请注意,您必须使用 apply / lambda 将 'sent_time' 系列的所有元素转换为单独的时区,因为该方法仅将标量作为目标参数时区。