【问题标题】:How to get current time in india in python如何在python中获取印度的当前时间
【发布时间】:2020-12-17 01:25:20
【问题描述】:

如何获取印度 python 中的当前时间戳?

我试过time.ctime()datetime.utcnow()还有datetime.now() 但他们返回的时间都与印度不同。

上面的代码返回的时间与我计算机上的当前时间不匹配。而且我电脑里的时间绝对是对的。

【问题讨论】:

标签: python python-3.x time timestamp timezone


【解决方案1】:
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"

【讨论】:

  • 这实际上比您接受的答案要好...请参阅我的评论。
【解决方案2】:

您可以在 datetime 模块中使用 timedelta 对象:

由于印度标准时间 (IST) 比协调世界时 (UTC) 早 5.5 小时,我们可以将 UTC 时间改为 5 小时 30 分钟。

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}")

结果:-

UTC Time     - 12-Jul-21 11:23:53
Indian Time  - 12-Jul-21 16:53:53

【讨论】:

    【解决方案3】:

    你可以用 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)
    

    结果:

    2020-08-28 06:01:13.833290
    2020-08-28 11:31:13.833290+05:30
    

    【讨论】:

    猜你喜欢
    • 2019-07-04
    • 2017-08-02
    • 2020-12-19
    • 2017-10-01
    • 2019-07-08
    • 1970-01-01
    • 2011-04-06
    相关资源
    最近更新 更多