简体   繁体   中英

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

I want to get the current time in the UTC offset +04:30, and can not find any function in the documentation of the datetime module that can open up the time for opening up the time zone. I don't want to use pytz since I want my program based on user inputs. How can I do that?

you can create a static time zone from a timedelta :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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