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}'
Index | Attribute | Values |
---|---|---|
0 | tm_year | (for example, 1993) |
1 | tm_mon | range [1, 12] |
2 | tm_mday | range [1, 31] |
3 | tm_hour | range [0, 23] |
4 | tm_min | range [0, 59] |
5 | tm_sec | range [0, 61] |
6 | tm_wday | range [0, 6], Monday is 0 |
7 | tm_yday | range [1, 366] |
8 | tm_isdst | 0, 1 or -1 |
N/A | tm_zone | abbreviation of timezone name |
N/A | tm_gmtoff | offset east of UTC in seconds |
No comments :
Post a Comment