Python get current time in right timezone

This question already has an answer here:

  • Display the time in a different time zone 6 answers

  • To get the current time in the local timezone as a naive datetime object:

    from datetime import datetime
    naive_dt = datetime.now()
    

    If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).

    To get the current time in UTC as a naive datetime object:

    naive_utc_dt = datetime.utcnow()
    

    To get the current time as an aware datetime object in Python 3.3+:

    from datetime import datetime, timezone
    
    utc_dt = datetime.now(timezone.utc) # UTC time
    dt = utc_dt.astimezone() # local time
    

    To get the current time in the given time zone from the tz database:

    import pytz
    
    tz = pytz.timezone('Europe/Berlin')
    berlin_now = datetime.now(tz)
    

    It works during DST transitions. It works if the timezone had different UTC offset in the past ie, it works even if the timezone corresponds to multiple tzinfo objects at different times.

    链接地址: http://www.djcxy.com/p/40918.html

    上一篇: 使用pyscopg2和PostgreSQL将datetime插入数据库

    下一篇: Python在正确的时区获得当前时间