Set timezone without changing time - Python

Viewed 2991

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.

1 Answers

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>)
Related