How to get the current time in Python

前端 未结 30 1810
滥情空心
滥情空心 2020-11-22 06:47

What is the module/method used to get the current time?

30条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 07:34

    I want to get the time with milliseconds. A simple way to get them:

    import time, datetime
    
    print(datetime.datetime.now().time())                         # 11:20:08.272239
    
    # Or in a more complicated way
    print(datetime.datetime.now().time().isoformat())             # 11:20:08.272239
    print(datetime.datetime.now().time().strftime('%H:%M:%S.%f')) # 11:20:08.272239
    
    # But do not use this:
    print(time.strftime("%H:%M:%S.%f", time.localtime()), str)    # 11:20:08.%f
    

    But I want only milliseconds, right? The shortest way to get them:

    import time
    
    time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 1000)
    # 11:34:23.751
    

    Add or remove zeroes from the last multiplication to adjust number of decimal points, or just:

    def get_time_str(decimal_points=3):
        return time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 10**decimal_points)
    

提交回复
热议问题