How do I print a datetime in the local timezone?

后端 未结 6 1965
夕颜
夕颜 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:26

    I believe the best way to do this is to use the LocalTimezone class defined in the datetime.tzinfo documentation (goto http://docs.python.org/library/datetime.html#tzinfo-objects and scroll down to the "Example tzinfo classes" section):

    Assuming Local is an instance of LocalTimezone

    t = datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=utc)
    local_t = t.astimezone(Local)
    

    then str(local_t) gives:

    '2009-07-11 04:44:59.193982+10:00'
    

    which is what you want.

    (Note: this may look weird to you because I'm in New South Wales, Australia which is 10 or 11 hours ahead of UTC)

提交回复
热议问题