0

I am currently having an issue with correct conversion of dates The localhost is running CET, when I create a UTC datetime and convert it to PST time it will return the default -8h (respective to UTC). This is generally true but right now there is the dailight savings offset UTC -> PST = -7 . Do I have to consider a special flag during the tz conversion?

In [3]: pytz.__version__                                                                                    
Out[3]: '2019.3'

In [5]: import datetime                                                                                     

In [6]: datetime.datetime.utcnow().astimezone(pytz.timezone('America/Los_Angeles'))                         
Out[6]: datetime.datetime(2021, 3, 23, 8, 53, 15, 833429, tzinfo=<DstTzInfo 'America/Los_Angeles' PDT-1 day, 17:00:00 DST>)

In [7]: !date                                                                                               
Tue 23 Mar 2021 05:53:20 PM CET

Code above should return 9AM , not 8AM.

El Dude
  • 5,328
  • 11
  • 54
  • 101
  • 3
    `utcnow()` returns naive datetime, use `datetime.datetime.now(datetime.timezone.utc)` instead. Side-note #1: your pytz version is outdated, the current one is 2021.1. Side-note #2: since Python 3.9, there's zoneinfo, which I think is a bit more convenient than pytz ([exemplary usage](https://stackoverflow.com/a/63628816/10197418)). – FObersteiner Mar 23 '21 at 17:00
  • 1
    Thanks. `datetime.timezone.utc` did the trick. Unfortunately I might not have control about the pytz version. Thanks for the `zoneinfo` pointer :) – El Dude Mar 23 '21 at 17:08
  • 1
    actually, you can simplify to e.g. `datetime.datetime.now(pytz.timezone('America/Los_Angeles'))` to get current time in a certain time zone. But the `utcnow` thing explains why this went wrong in the first place ;-) – FObersteiner Mar 24 '21 at 06:53
  • Thank you all. Bit puzzled why `utcnow` is naive. I knew `now` was so its clashing in my head. Something to memorize :) – El Dude Mar 24 '21 at 16:19
  • yeah, `utcnow` is weird, there's even [a blog post about it](https://blog.ganssle.io/articles/2019/11/utcnow.html). As long as you supply a time zone to `now`, it returns aware datetime (in that time zone). – FObersteiner Mar 24 '21 at 16:23

0 Answers0