Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert UTC timezone to IST python

The following code line gives me the UTC timing on the production server.

timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')

Please suggest a way to convert above UTC timezone to IST(Indian Standard Time) timing.

like image 441
Mahesh Avatar asked Jul 22 '20 21:07

Mahesh


People also ask

How do you convert UTC time to local time?

Add the local time offset to the UTC time. For example, if your local time offset is -5:00, and if the UTC time is shown as 11:00, add -5 to 11. The time setting when adjusted for offset is 06:00 (6:00 A.M.).


2 Answers

datetime.now() gives you a naive datetime object that represents local time according to the setting of the machine you run the script on (which in this case just happens to be UTC since it's a server). See the docs.

To get "now" in a specific timezone, you can set the tz property appropriately.

Python >= 3.9: you have zoneinfo in the standard lib to do this:

from zoneinfo import ZoneInfo
dtobj = datetime.now(tz=ZoneInfo('Asia/Kolkata'))
print(dtobj)
>>> 2020-07-23 11:11:43.594442+05:30

Python < 3.9: I'd recommend the dateutil package to do so (or use zoneinfo via backports.zoneinfo).

from datetime import datetime
from dateutil.tz import gettz
dtobj = datetime.now(tz=gettz('Asia/Kolkata'))
print(dtobj)
>>> 2020-07-23 11:08:54.032651+05:30
like image 83
FObersteiner Avatar answered Oct 17 '22 05:10

FObersteiner


from datetime import datetime    
import pytz    
tz_NY = pytz.timezone('Asia/Kolkata')   
datetime_NY = datetime.now(tz_NY)  
print("India time:", datetime_NY.strftime("%Y-%m-%d %H:%M:%S.%f"))       
>>India time: 2021-05-03 12:25:21.877976
like image 8
Nishtha Avatar answered Oct 17 '22 07:10

Nishtha