5

Seemingly simple but I cannot get it to work. I have tried pytz.timezone('timezone').localize(dt.datetime().now()), dt.datetime.now().astimezone(pytz.timezone('timezone')) along with many other snippets, however they all create the a datetime object that is <my time>+/-timedifference.

How do I simply set the timezone of a datetime object to literally make it the timezone's time?

Edit:

Sorry for the confusion, the problem was to do with the time I was getting from my Postgres database. I thought the time was naive, however postgres was actually aware of the time and was returning it in UTC.

Fred Peters
  • 91
  • 1
  • 7

1 Answers1

10

Something like this ?

[Edited to show better examples]

dt.datetime.now()
> datetime.datetime(2020, 10, 16, 15, 33, 16, 7064)

dt.datetime.now().replace(tzinfo=pytz.timezone('Pacific/Fiji'))
> datetime.datetime(2020, 10, 16, 15, 33, 18, 906361, tzinfo=<DstTzInfo 'Pacific/Fiji' LMT+11:56:00 STD>)

dt.datetime.now().replace(tzinfo=pytz.timezone('Europe/Stockholm'))
> datetime.datetime(2020, 10, 16, 15, 33, 21, 817528, tzinfo=<DstTzInfo 'Europe/Stockholm' LMT+1:12:00 STD>)
JoseKilo
  • 2,343
  • 1
  • 16
  • 28
  • 1
    This will give you LMT for time zones that are not UTC/GMT. Btw. EST is not a time zone, it's just in the pytz database for historical reasons. – FObersteiner Oct 16 '20 at 14:27
  • You're right, but the resulting objects have the same hour/minute/etc (which I believe is the original question). It's just the time-zone object that has a different representation. Am I missing something ? – JoseKilo Oct 16 '20 at 14:37
  • 4
    here's a [nice blog post](https://blog.ganssle.io/articles/2018/03/pytz-fastest-footgun.html) that gives some background on this pytz "feature". Replace works correctly if you use dateutil or zoneinfo (py 3.9) to obtain the tz object. However, reading the question again, it seems the OP whats something else (see my comment on the question). – FObersteiner Oct 16 '20 at 15:47
  • Note that if dt_obj = dt.datetime.now(), then dt_obj.replace(..) doesn't work. **It needs to be in one go:** dt_obj = dt.datetime.now().replace(..) – DZet Nov 21 '22 at 21:03