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

2 Answers2

3

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,509
  • 2
  • 15
  • 23
  • Thank you! That's what I needed to know, whether it's worth doing it natively haha –  Dec 12 '18 at 19:34
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
  • 167
  • 2
  • 14