python: datetime tzinfo time zone names documentation

后端 未结 3 1283
悲哀的现实
悲哀的现实 2020-12-13 19:51

I have a date that I build:

from datetime import datetime
from datetime import tzinfo
test = \'2013-03-27 23:05\'
test2 = datetime.strptime(test,\'%Y-%m-%d %         


        
相关标签:
3条回答
  • 2020-12-13 20:12
     import pytz
     timezones=pytz.all_timezones
    

    This gives all timezones

    0 讨论(0)
  • 2020-12-13 20:16

    The standard library does not define any timezones -- at least not well (the toy example given in the documentation does not handle subtle problems like the ones mentioned here). For predefined timezones, use the third-party pytz module.

    import pytz
    import datetime as DT
    
    eastern = pytz.timezone('US/Eastern')
    utc = pytz.utc
    test = '2013-03-27 23:05'
    

    This is a "naive" datetime:

    test2 = DT.datetime.strptime(test, '%Y-%m-%d %H:%M')   
    print(test2)
    # 2013-03-27 23:05:00
    

    This makes a timezone-aware datetime by interpreting test2 as if it were in the EST timezone:

    print(eastern.localize(test2))
    # 2013-03-27 23:05:00-04:00
    

    This makes a timezone-aware datetime by interpreting test2 as if it were in the UTC timezone:

    print(utc.localize(test2))
    # 2013-03-27 23:05:00+00:00
    

    Alternatively, you can convert one timezone-aware datetime to another timezone using the astimezone method:

    test2_eastern = eastern.localize(test2)
    print(test2_eastern.astimezone(utc))
    # 2013-03-28 03:05:00+00:00
    
    0 讨论(0)
  • 2020-12-13 20:24

    since the release of Python 3.9, the standard lib does define time zones, and you can get them via

    import zoneinfo
    print(zoneinfo.available_timezones())
    
    # {'America/Belem', 'Asia/Tel_Aviv', 'Australia/North', 'Asia/Omsk', 
    #  'Europe/Isle_of_Man', 'America/New_York', 'Europe/Nicosia', 
    #  'Pacific/Funafuti', 'America/Ensenada', 'Europe/Mariehamn', 
    #  'America/Maceio', 'America/Guatemala', 'America/Guadeloupe', ...
    

    docs

    0 讨论(0)
提交回复
热议问题