Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set timezone without changing time - Python

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.

like image 835
Fred Peters Avatar asked May 14 '26 11:05

Fred Peters


1 Answers

Something like this ?

[Edited to show better examples]

[Edited to include zoneinfo version]

New zoneinfo based version (it requires Python version 3.9 or newer):

dt.datetime.now()
> datetime.datetime(2024, 8, 30, 11, 57, 35, 442646)

dt.datetime.now().replace(tzinfo=zoneinfo.ZoneInfo('Pacific/Fiji'))
> datetime.datetime(2024, 8, 30, 11, 57, 38, 873377, tzinfo=zoneinfo.ZoneInfo(key='Pacific/Fiji'))

dt.datetime.now().replace(tzinfo=zoneinfo.ZoneInfo('Europe/Stockholm'))
> datetime.datetime(2024, 8, 30, 11, 57, 40, 455853, tzinfo=zoneinfo.ZoneInfo(key='Europe/Stockholm'))

Old pytz based version:

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>)
like image 81
JoseKilo Avatar answered May 17 '26 01:05

JoseKilo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!