【问题标题】:How to get local time in python如何在python中获取当地时间
【发布时间】:2022-01-17 00:08:16
【问题描述】:

我怎么能得到当地时间,比如现在是 9:06 对于我的朋友来说,现在是 6:06。 我怎么能在python中得到那个时间。 我曾尝试使用 DateTime,但没有找到一种方法来做到这一点。

【问题讨论】:

标签: python time


【解决方案1】:

您可以使用 pytz 库。

from datetime import datetime
import pytz

datetime_NewYork = datetime.now(pytz.timezone('America/New_York'))
print("NY time:", datetime_NewYork.strftime("%H:%M:%S"))

datetime_London = datetime.now(pytz.timezone('Europe/London'))
print("London time:", datetime_London.strftime("%H:%M:%S"))

【讨论】:

    【解决方案2】:

    如果您想获取当前时间,您是想获取您的当前时间,还是您朋友的当前时间:

    from datetime import datetime
        
    now = datetime.now()
        
    current_time = now.strftime("%H:%M:%S")
        
    print("Current Time is :", current_time)
    

    只是一个忠告,我用了 2 秒的时间来谷歌这个,我知道你是新人,虽然这种问题可能会给你带来麻烦。

    【讨论】:

      【解决方案3】:

      你可以使用时间库,和localtime()/asctime()函数。

      
      import time
      
      # This will give you o/p in the format of
      # time.struct_time(tm_year=2022, tm_mon=1, tm_mday=16, tm_hour=19, tm_min=14, tm_sec=39, tm_wday=6, tm_yday=16, tm_isdst=0)
      print(time.localtime())
      
      # This will give you o/p in more simpler manner
      # 'Sun Jan 16 19:15:01 2022'
      print(time.asctime())
      
      

      你也可以使用time.time(),但是你必须在之后进行转换。

      【讨论】:

        【解决方案4】:

        也许这会有所帮助。

        from datetime import datetime
        
        now = datetime.now()
        
        current_time = now.strftime("%H:%M:%S")
        print("Current Time =", current_time)
        

        【讨论】:

          【解决方案5】:

          time.localtime() 返回当地时间。

          【讨论】:

            猜你喜欢
            • 2010-10-14
            • 1970-01-01
            • 2017-08-02
            • 2014-07-06
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多