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!
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.
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)
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'))
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!
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.
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)
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'))