How would I get the current timestamp in python of India?
I tried time.ctime() and datetime.utcnow() also datetime.now() but they all return a different time than here it is in india.
The codes above return the time that not match the current time on my computer. and the time in my computer is definitely correct.
33 Answers
from pytz import timezone from datetime import datetime ind_time = datetime.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d %H:%M:%S.%f') print(ind_time) >>> "2020-08-28 11:56:37.010822" 1You can use timedelta object in datetime module:
since the Indian Standard Time (IST) is 5.5 hours ahead of Coordinated Universal Time (UTC), we can shift the UTC time to 5hrs and 30 mins.
import datetime as dt dt_India = dt.datetime.utcnow() + dt.timedelta(hours=5, minutes=30) Indian_time = dt_India.strftime('%d-%b-%y %H:%M:%S') UTC_time = dt.datetime.utcnow().strftime('%d-%b-%y %H:%M:%S') max_len = len(max(['UTC Time', 'Indian Time'], key=len)) print(f"{'UTC Time' :<{max_len}} - {UTC_time}") print(f"{'Indian Time':<{max_len}} - {Indian_time}") Result:-
UTC Time - 12-Jul-21 11:23:53 Indian Time - 12-Jul-21 16:53:53 You can do it with pytz:
import datetime,pytz dtobj1=datetime.datetime.utcnow() #utcnow class method print(dtobj1) dtobj3=dtobj1.replace(tzinfo=pytz.UTC) #replace method #print(pytz.all_timezones) => To see all timezones dtobj_india=dtobj3.astimezone(pytz.timezone("Asia/Calcutta")) #astimezone method print(dtobj_india) result:
2020-08-28 06:01:13.833290 2020-08-28 11:31:13.833290+05:30 1