Python timezone conversion adding minutes to the hour?

后端 未结 1 420
执笔经年
执笔经年 2021-01-24 16:41

So I\'m trying to convert a bunch of hours (10:00:00, 14:00:00, etc) from a given timezone to UTC.

When I do so, I keep maddeningly getting things back like \"15:51:00\"

相关标签:
1条回答
  • 2021-01-24 17:05

    You are not specifying a date when you create the jj datetime object, so the default date of 1900-01-01 is used. Timezones are not fixed entities; they change over time, and the US/Central timezone used a different offset back in 1900.

    At the very least, use a recent date, like today for example:

    # use today's date, with the time from jj, and a given timezone.
    datetime.datetime.combine(datetime.date.today(), jj.time(), tzinfo=tzz)
    

    If all you need is a time, then don't create datetime objects to store those; the datetime module has a dedicated time() object. I'd also not use strftime() to create objects from literals. Just use the constructor to pass in integers:

    jj = datetime.time(10, 0, 0)  # or just .time(10)
    

    Other good rules of thumb: If you have to deal with dates with timezones, try to move those to datetime objects in UTC the moment your code receives or loads them. If you only have a time of day, but still need timezone support, attach them to today's date, so you get the right timezone. Only convert to strings again as late as possible.

    0 讨论(0)
提交回复
热议问题