Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert US/Eastern timezone to US/Central in Python

I'm trying to convert a 'US/Eastern' datetime to be the equivalent for another timezone, like 'US/Central'. It seems that using pytz and astimezone would be a good way to do this from: Converting timezone-aware datetime to local time in Python

import pytz
import datetime as DT
est = pytz.timezone('US/Eastern')
cst = pytz.timezone('US/Central')

I create a datetime object for est:

ny_dt = DT.datetime(2021, 3, 1, 9, 30, 0, 0, est)

Here's the output for ny_dt:

Out[6]: datetime.datetime(2021, 3, 1, 9, 30, tzinfo=<DstTzInfo 'US/Eastern' LMT-1 day, 19:04:00 STD>)

I then try to convert this datetime to instead use the defined cst timezone:

chicago_dt = ny_dt.astimezone(cst)

Here's the output for chicago_dt:

Out[8]: datetime.datetime(2021, 3, 1, 8, 26, tzinfo=<DstTzInfo 'US/Central' CST-1 day, 18:00:00 STD>)

So this converted 930am EST to be 826am CST, which is not correct. It should be 830am CST, or exactly one hour earlier. What is the best way to do this? Thanks!

like image 686
AaronE Avatar asked Apr 29 '26 22:04

AaronE


1 Answers

import pytz
import datetime as DT
est = pytz.timezone('US/Eastern')
cst = pytz.timezone('US/Central')
ny_dt = DT.datetime(2021, 3, 1, 9, 30, 0, 0)
ny_dt1 = est.localize(ny_dt)
chicago_dt = ny_dt1.astimezone(cst)

Output:

ny_dt1
datetime.datetime(2021, 3, 1, 9, 30, tzinfo=<DstTzInfo 'US/Eastern' EST-1 day, 19:00:00 STD>)
chicago_dt
datetime.datetime(2021, 3, 1, 8, 30, tzinfo=<DstTzInfo 'US/Central' CST-1 day, 18:00:00 STD>)

From the documentation

This library differs from the documented Python API for tzinfo implementations; if you want to create local wallclock times you need to use the localize() method documented in this document.

like image 110
Ajay Avatar answered May 02 '26 10:05

Ajay



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!