5

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.

Akash Maurya
  • 344
  • 1
  • 2
  • 10
  • 1
    datetime.now() will return the correct time if your computer's date/time is set correctly. – Selcuk Aug 28 '20 at 05:56
  • 4
    Does this answer your question? [Display the time in a different time zone](https://stackoverflow.com/questions/1398674/display-the-time-in-a-different-time-zone) – seven_seas Aug 28 '20 at 05:57
  • 1
    save yourself some trouble and skip using pytz, see my [answer here](https://stackoverflow.com/a/63628816/10197418). – FObersteiner Aug 28 '20 at 07:07

3 Answers3

15
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"
Akash Maurya
  • 344
  • 1
  • 2
  • 10
3

You 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_naive = dt.datetime.utcnow() + dt.timedelta(hours=5, minutes=30)
dt_India_aware = dt.datetime.now(dt.timezone(dt.timedelta(hours=5, minutes=30)))

dt_UTC_naive = dt.datetime.utcnow()
dt_UTC_aware = dt.datetime.now(dt.timezone.utc)

max_len = len(max(['UTC Time', 'Indian Time'], key=len))

print(f"{'UTC Time'   :<{max_len}} - {dt_UTC_aware:%d-%b-%y %H:%M:%S}")
print(f"{'Indian Time':<{max_len}} - {dt_India_aware:%d-%b-%y %H:%M:%S}")

# Both offset-naive and offset-aware will provide same results in this sitatuiion

Result:-

UTC Time    - 20-Feb-23 03:29:12
Indian Time - 20-Feb-23 08:59:12
Ashik Mydeen
  • 104
  • 7
2

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
Renaud
  • 2,709
  • 2
  • 9
  • 24
  • utcnow() can be pretty misleading, -> [stop using utcnow and utcfromtimestamp](https://blog.ganssle.io/articles/2019/11/utcnow.html) – FObersteiner Aug 28 '20 at 07:08