Python about conversion between various time formats

During the recent coding period, I was a little confused by the time format conversion. In fact, I was still a little unfamiliar with the conversion between several commonly used time formats. The most commonly used times are:

1. Timestamp

2. Time of type struct_time

3. datetime time format

4. Format the time string

Next, I will analyze the function usage mainly involved in the time format of each format.

1. Timestamp

Timestamp is an object of float and int type. The easiest way to get timestamp is the time module time.time() function to get the current timestamp, and then we can use the acquired timestamp to perform various conversions.

1.1 Time stamp to stuct_time type: time.gmtime (time stamp)

>>> now_ts = time.gmtime(time.time())
>>> now_ts
time.struct_time(tm_year=2018, tm_mon=5, tm_mday=6, tm_hour=8, tm_min=13, tm_sec=26, tm_wday=6, tm_yday=126, tm_isdst=0)

1.2 Time stamp converted to datetime format: use datetime.fromtimestamp of datetime module

>>> from datetime import datetime
>>> datetime.fromtimestamp(time.time())
datetime.datetime(2018, 5, 6, 17, 58, 36, 644783)

2. Time of type struct_time

2.1 Time-to-timestamp of stuct_time type: time.mktime (time of stuct_time type)

>>> date_to_ts = time.mktime(time.localtime())

>>> date_to_ts

1525594605.0

Three formatted time strings

3.1 Output string in time format: time format time.strftime('%Y-%m-%d %H:%M%S')

>>> datetime.now().strftime('%Y-%m-%d %H:%M:%S')
'2018-05-06 18:38:02'

Four datetime format time

4.1 Output the current time: datetime.now()

4.2 Convert string format time to datetime format time: datetime.strptime(time_str, '%Y-%m-%d %H:%M%S')

4.3 Output at specified time

>>> datetime(2018,5,6,00,00,00)
datetime.datetime(2018, 5, 6, 0, 0)


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325389661&siteId=291194637