繁体   English   中英

Python - 如何将日期时间对象转换为列中作为字符串给出的时区?

[英]Python - How to convert datetime object to timezone given as string in a column?

我有一列 UTC 时间,我需要根据第二列中作为字符串提供的 UTC 时区将其转换为“本地”时间。 如何使用pytz根据提供的字符串 UTC 时区将时区分配给列中的时间? 在此处输入图像描述

import pytz

# fmt: Etc/GMT{+,-}{tm}
def format_tz(s:str):
    icon = '+' # default to plus sign
    s = s.strip()
    if s[0] == '-':
        icon = '-' # change to minus if is minus
    if s[0] in ('+', '-'):
        s = s[1:] # strip pluses and minuses
    i:int = int(s) # change to integer
    return pytz.timezone(f'Etc/GMT{icon}{i}') # convert to timezone

和时间(不包括毫秒)

# fmt: yyyy-mm-dd hh:mm:ss.MMM
def format_time(s:str):
    return time.strptime(s[:-5], '%Y-%m-%d %H:%M:%S')

将日期/时间列解析为 datetime 对于 UTC(偏移量)列执行相同的操作,但只保留偏移量。 然后将此偏移量转换为时区。 前任:

import pandas as pd

df = pd.DataFrame({"bed_time": ["2021-03-28 00:40:00.000","2021-03-28 06:00:00.000"],
                   "wake_time": ["2021-03-27 00:00:00.000","2021-03-27 08:10:00.000"],
                   "UTC": ["+0400","+0500"]}) # adjusted example here to take mixed UTC offsets in to account

# parse to UTC and get the tz as a fixed offset
df['bed_time'] = pd.to_datetime(df['bed_time'], utc=True)
df['wake_time'] = pd.to_datetime(df['wake_time'], utc=True)
df['offset'] = pd.to_datetime(df['UTC'], format='%z').apply(lambda t: t.tz)

现在我们有了 UTC 和一个固定的偏移时区;

df
                   bed_time  ...                 offset
0 2021-03-28 00:40:00+00:00  ...  pytz.FixedOffset(240)
1 2021-03-28 06:00:00+00:00  ...  pytz.FixedOffset(300)

所以我们可以转换成那个;

# convert to tz individually
df['bed_time'] = df.apply(lambda row: row['bed_time'].tz_convert(row['offset']), axis=1)
df['wake_time'] = df.apply(lambda row: row['wake_time'].tz_convert(row['offset']), axis=1)

要得到

df
                    bed_time  ...                 offset
0  2021-03-28 04:40:00+04:00  ...  pytz.FixedOffset(240)
1  2021-03-28 11:00:00+05:00  ...  pytz.FixedOffset(300)
tz = timezone('America/New_York')

pytz.utc.localize(utc_time, is_dst=None).astimezone(tz)

astimezone() 会将其转换为您选择的时区。 utc_time 变量是您的 UTC 字符串,而 tz 是您希望将其转换为的时区。 这里有一个所有 pytz 时区的列表: timezone list

另外,请参阅this thread, 这里有更多答案

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM