How to get the current time in Python

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

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

相关标签:
30条回答
  • 2020-11-22 07:36

    Because no one has mentioned it yet, and this is something I ran into recently... a pytz timezone's fromutc() method combined with datetime's utcnow() is the best way I've found to get a useful current time (and date) in any timezone.

    from datetime import datetime
    
    import pytz
    
    
    JST = pytz.timezone("Asia/Tokyo")
    
    
    local_time = JST.fromutc(datetime.utcnow())
    

    If all you want is the time, you can then get that with local_time.time().

    0 讨论(0)
  • 2020-11-22 07:37

    Do

    from time import time
    
    t = time()
    
    • t - float number, good for time interval measurement.

    There is some difference for Unix and Windows platforms.

    0 讨论(0)
  • 2020-11-22 07:38
    from datetime import datetime
    datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    

    For this example, the output will be like this: '2013-09-18 11:16:32'

    Here is the list of strftime directives.

    0 讨论(0)
  • 2020-11-22 07:38

    Using pandas to get the current time, kind of overkilling the problem at hand:

    import pandas as pd
    print(pd.datetime.now())
    print(pd.datetime.now().date())
    print(pd.datetime.now().year)
    print(pd.datetime.now().month)
    print(pd.datetime.now().day)
    print(pd.datetime.now().hour)
    print(pd.datetime.now().minute)
    print(pd.datetime.now().second)
    print(pd.datetime.now().microsecond)
    

    Output:

    2017-09-22 12:44:56.092642
    2017-09-22
    2017
    9
    22
    12
    44
    56
    92693
    
    0 讨论(0)
  • 2020-11-22 07:38

    Try the arrow module from http://crsmithdev.com/arrow/:

    import arrow
    arrow.now()
    

    Or the UTC version:

    arrow.utcnow()
    

    To change its output, add .format():

    arrow.utcnow().format('YYYY-MM-DD HH:mm:ss ZZ')
    

    For a specific timezone:

    arrow.now('US/Pacific')
    

    An hour ago:

    arrow.utcnow().replace(hours=-1)
    

    Or if you want the gist.

    arrow.get('2013-05-11T21:23:58.970460+00:00').humanize()
    >>> '2 years ago'
    
    0 讨论(0)
  • 2020-11-22 07:39
    import datetime
    
    todays_date = datetime.date.today()
    print(todays_date)
    >>> 2019-10-12
    
    # adding strftime will remove the seconds
    current_time = datetime.datetime.now().strftime('%H:%M')
    print(current_time)
    >>> 23:38
    
    0 讨论(0)
提交回复
热议问题