How to get the current time in Python

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

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

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

    Similar to Harley's answer, but use the str() function for a quick-n-dirty, slightly more human readable format:

    >>> from datetime import datetime
    >>> str(datetime.now())
    '2011-05-03 17:45:35.177000'
    
    0 讨论(0)
  • 2020-11-22 07:16

    You can use the time module:

    import time
    print time.strftime("%d/%m/%Y")
    
    >>> 06/02/2015
    

    The use of the capital Y gives the full year, and using y would give 06/02/15.

    You could also use the following code to give a more lengthy time:

    time.strftime("%a, %d %b %Y %H:%M:%S")
    >>> 'Fri, 06 Feb 2015 17:45:09'
    
    0 讨论(0)
  • 2020-11-22 07:18

    The quickest way is:

    >>> import time
    >>> time.strftime("%Y%m%d")
    '20130924'
    
    0 讨论(0)
  • 2020-11-22 07:18

    If you just want the current timestamp in ms (for example, to measure execution time), you can also use the "timeit" module:

    import timeit
    start_time = timeit.default_timer()
    do_stuff_you_want_to_measure()
    end_time = timeit.default_timer()
    print("Elapsed time: {}".format(end_time - start_time))
    
    0 讨论(0)
  • 2020-11-22 07:20

    The previous answers are all good suggestions, but I find it easiest to use ctime():

    In [2]: from time import ctime
    In [3]: ctime()
    Out[3]: 'Thu Oct 31 11:40:53 2013'
    

    This gives a nicely formatted string representation of the current local time.

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

    if you are using numpy already then directly you can use numpy.datetime64() function.

    import numpy as np
    str(np.datetime64('now'))
    

    for only date:

    str(np.datetime64('today'))
    

    or, if you are using pandas already then you can use pandas.to_datetime() function

    import pandas as pd
    str(pd.to_datetime('now'))
    

    or,

    str(pd.to_datetime('today'))
    
    0 讨论(0)
提交回复
热议问题