How do I print a datetime in the local timezone?

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

    I wrote something like this the other day:

    import time, datetime
    def nowString():
        # we want something like '2007-10-18 14:00+0100'
        mytz="%+4.4d" % (time.timezone / -(60*60) * 100) # time.timezone counts westwards!
        dt  = datetime.datetime.now()
        dts = dt.strftime('%Y-%m-%d %H:%M')  # %Z (timezone) would be empty
        nowstring="%s%s" % (dts,mytz)
        return nowstring
    

    So the interesting part for you is probably the line starting with "mytz=...". time.timezone returns the local timezone, albeit with opposite sign compared to UTC. So it says "-3600" to express UTC+1.

    Despite its ignorance towards Daylight Saving Time (DST, see comment), I'm leaving this in for people fiddling around with time.timezone.

提交回复
热议问题