python: datetime tzinfo time zone names documentation

后端 未结 3 1287
悲哀的现实
悲哀的现实 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: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
    

提交回复
热议问题