簡體   English   中英

如何在日期時間模塊 python 中獲取時區的特定 UTC 時間

[英]how do I get the specific UTC time of a time zone in datetime module python

我想在UTC偏移+04:30獲取當前時間,在datetime模塊的文檔中找不到可以打開時區時間的function。 我不想使用pytz ,因為我希望我的程序基於用戶輸入。 我怎樣才能做到這一點?

您可以從timedelta創建 static 時區:

from datetime import datetime, timezone, timedelta

# let's make this a function so it is more generally useful...
def offset_to_timezone(offset_string):
    """
    a function to convert a UTC offset string '+-hh:mm'
    to a static time zone.
    """
    # check if the offset is forward or backward in time
    direction = 1 if offset.startswith('+') else -1
    # to hours, minutes, excluding the "direction"
    off_hours, off_minutes = map(int, offset[1:].split(':'))
    # create a timezone object from the static offset
    return timezone(timedelta(hours=off_hours, minutes=off_minutes)*direction)

# you can also make use of datetime's strptime:
def offset_to_tz_strptime(offset_string):
    """
    make use of datetime.strptime to do the same as offset_to_timezone().
    """
    return datetime.strptime(offset_string, "%z").tzinfo

# call it e.g. as    
for offset in ('+04:30', '-04:30'):
    tz = offset_to_timezone(offset)
    print(f"now at UTC{offset}: {datetime.now(tz).isoformat(timespec='seconds')}")
now at UTC+04:30: 2021-03-28T16:30:21+04:30
now at UTC-04:30: 2021-03-28T07:30:21-04:30

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM