How do I print a datetime in the local timezone?

后端 未结 6 1964
夕颜
夕颜 2020-12-03 06:38

Let\'s say I have a variable t that\'s set to this:

datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=)

If I say s

6条回答
  •  鱼传尺愫
    2020-12-03 07:19

    This script demonstrates a few ways to show the local timezone using astimezone():

    #!/usr/bin/env python3
    
    import pytz
    from datetime import datetime, timezone
    from tzlocal import get_localzone
    
    utc_dt = datetime.now(timezone.utc)
    
    PST = pytz.timezone('US/Pacific')
    EST = pytz.timezone('US/Eastern')
    JST = pytz.timezone('Asia/Tokyo')
    NZST = pytz.timezone('Pacific/Auckland')
    
    print("Pacific time {}".format(utc_dt.astimezone(PST).isoformat()))
    print("Eastern time {}".format(utc_dt.astimezone(EST).isoformat()))
    print("UTC time     {}".format(utc_dt.isoformat()))
    print("Japan time   {}".format(utc_dt.astimezone(JST).isoformat()))
    
    # Use astimezone() without an argument
    print("Local time   {}".format(utc_dt.astimezone().isoformat()))
    
    # Use tzlocal get_localzone
    print("Local time   {}".format(utc_dt.astimezone(get_localzone()).isoformat()))
    
    # Explicitly create a pytz timezone object
    # Substitute a pytz.timezone object for your timezone
    print("Local time   {}".format(utc_dt.astimezone(NZST).isoformat()))
    

    It outputs the following:

    $ ./timezones.py 
    Pacific time 2019-02-22T17:54:14.957299-08:00
    Eastern time 2019-02-22T20:54:14.957299-05:00
    UTC time     2019-02-23T01:54:14.957299+00:00
    Japan time   2019-02-23T10:54:14.957299+09:00
    Local time   2019-02-23T14:54:14.957299+13:00
    Local time   2019-02-23T14:54:14.957299+13:00
    Local time   2019-02-23T14:54:14.957299+13:00
    

    As of python 3.6 calling astimezone() without a timezone object defaults to the local zone (docs). This means you don't need to import tzlocal and can simply do the following:

    #!/usr/bin/env python3
    
    from datetime import datetime, timezone
    
    utc_dt = datetime.now(timezone.utc)
    
    print("Local time {}".format(utc_dt.astimezone().isoformat()))
    

提交回复
热议问题