How to get current time in a specific timezone?

Question:

I am using the datetime module as follows to get the current time:

 datetime.now().strftime('%I:%M:%S %p')

And this gives me the current time but in UTC. How can I get the current time in CST ?
Can I do that without using other external libraries or is it easier to use something else?

Any help is appreciated!

Asked By: user10658941

||

Answers:

It might be tricky without an external library, so i suggest you use the pytz package

pip install pytz

And with help from here you could try something like below

from datetime import datetime
from pytz import timezone

now_time = datetime.now(timezone('America/Chicago'))
print(now_time.strftime('%I:%M:%S %p'))

I used America/Chicago because it’s in the CDT timezone according to this.

But if you are interested in doing it natively you will have to read up some more here in the official documentation because it provide some examples on how to do it but it will leave kicking and screaming especially if you are a beginner.

Answered By: kellymandem

Well, this solution depends on the module pytz

import pytz
import datetime

print(datetime.datetime.now(pytz.timezone('US/Central')))

In case you need to know all available timezones

for tz in pytz.all_timezones:
    print(tz)
Answered By: Yi Bao

Here’s how to do it without an external library or hard-coding the offset

from zoneinfo import ZoneInfo
time_stamp = datetime.now(ZoneInfo('America/Chicago'))
Answered By: toddmo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.