1

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!

  • Possible duplicate of [Python Timezone conversion](https://stackoverflow.com/questions/10997577/python-timezone-conversion) – d_kennetz Dec 12 '18 at 16:42

3 Answers3

4

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.

kellymandem
  • 1,709
  • 3
  • 17
  • 27
  • Thank you! That's what I needed to know, whether it's worth doing it natively haha –  Dec 12 '18 at 19:34
  • 1
    Things got easier in 3.9. [My answer on this question](https://stackoverflow.com/a/74237887/1045881) – toddmo Oct 28 '22 at 15:57
1

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)
Yi Bao
  • 165
  • 2
  • 15
1

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'))
toddmo
  • 20,682
  • 14
  • 97
  • 107