21 Oct 2022

Get Date and Time String in Python

收藏到CSDN网摘

It's a very common task that you may need the current date and time as a string, which can then be assigned as a timestamp for logging, intermidiate input deck generation, etc. In Python, there are several modules available to achieve this, such as date, time, datetime - well, it looks redudent here! The easierest way might be using the time module. To get the time, all we need to do is to get a time object using the function 'time.localtime()'. The input is optional as the return value of 'time.time()' which is the current time as a floating point number would be used if it's omitted or None. Then, all the fields can be accessed by the field names although most of them can also be accessed via an index (it's not recommended to use index anyway). A simple example is shown below:
def get_time_str():
    ''' get the current time in the format of dd-mm-yyyy hh:mm:ss '''
    timeObj = time.localtime(time.time())
    return f'{timeObj.tm_year}{timeObj.tm_mon:02d}{timeObj.tm_mday:02d}T{timeObj.tm_hour:02d}{timeObj.tm_min:02d}{timeObj.tm_sec:02d}'
IndexAttributeValues
0tm_year(for example, 1993)
1tm_monrange [1, 12]
2tm_mdayrange [1, 31]
3tm_hourrange [0, 23]
4tm_minrange [0, 59]
5tm_secrange [0, 61]
6tm_wdayrange [0, 6], Monday is 0
7tm_ydayrange [1, 366]
8tm_isdst0, 1 or -1
N/Atm_zoneabbreviation of timezone name
N/Atm_gmtoffoffset east of UTC in seconds

No comments :

Post a Comment