How do I print a datetime in the local timezone?

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

    As of python 3.2, using only standard library functions:

    u_tm = datetime.datetime.utcfromtimestamp(0)
    l_tm = datetime.datetime.fromtimestamp(0)
    l_tz = datetime.timezone(l_tm - u_tm)
    
    t = datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=l_tz)
    str(t)
    '2009-07-10 18:44:59.193982-07:00'
    

    Just need to use l_tm - u_tm or u_tm - l_tm depending whether you want to show as + or - hours from UTC. I am in MST, which is where the -07 comes from. Smarter code should be able to figure out which way to subtract.

    And only need to calculate the local timezone once. That is not going to change. At least until you switch from/to Daylight time.

提交回复
热议问题