【问题标题】:How can I get a datetime hour in python for a specific timezone?如何在 python 中获取特定时区的日期时间?
【发布时间】:2020-03-18 03:31:56
【问题描述】:

我有一个 UTC 日期时间,但我需要根据任何给定的时区字符串获取数字小时,即:'America/Los_Angeles'

我需要一个看起来像这样的函数:

def get_hour_timezone(utc_datetime, timezone):
    return utc_datetime.hour(AT_SPECIFIC_TIMEZONE)


get_hour_timezone(now(), 'America/Los_Angeles') # This should return 5, because it's 5 AM

get_hour_timezone(now(), 'UTC') # This should return 12, because it's 12 PM (7 hours past Los Angeles because it's utc)

我也需要相同的月和日函数(如果洛杉矶时间是当月最后一天的晚上 11 点,但下个月的 UTC 时间是凌晨 2 点)

【问题讨论】:

    标签: python datetime timezone


    【解决方案1】:

    解决方案是首先将日期时间转换为特定时区。

    def get_datetime_with_timezone(dt, tz):
        local_timezone = timezone(tz)
        if dt.tzinfo is None:
            datetime_aware = local_timezone.localize(dt)
        else:
            datetime_aware = dt.astimezone(local_timezone)
        return datetime_aware
    

    【讨论】:

      猜你喜欢
      • 2016-03-12
      • 2011-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-23
      • 2020-06-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多