Time Conversion
When processing time in Python, the most common is the conversion between the character form and the timestamp. Put the most basic conversions down here.
String--Timestamp
import timeimport dateutil.parser as dateparserdef str_to_timestamp(time_str) dt = dateparser.parse(time_str) # OR: dt = time.strptime(datetimestring, fmt) return time.mktime(dt.timetuple())datetimestring = ‘Fri, 08 Jun 2012 22:40:26 GMT‘str_to_timestamp(datetimestring)
Timestamp, string
import timedef timestamp_to_str(ts, fmt=‘%Y-%m-%d %H:%M:%S‘): return time.strftime(fmt, time.localtime(timestamp))timestamp = time.time()timestamp_to_str(timestamp)
Python built-in time data structure
Python internally uses a data structure similar to Namedtuple to store time. This data structure has 9 fields that can be accessed with a numeric subscript or by name.
time.struct_time( tm_year=2014, tm_mon=9, tm_mday=1, tm_hour=9, tm_min=0, tm_sec=0, tm_wday=0, # 星期几, 0~6 tm_yday=244, # 本年的第几天, 1~366 tm_isdst=0 # 是否夏令时 )
Timestamp's Notes
Here is a small detail, the time stamp is based on the standard Time zone, and Beijing time has 8 hours of jet lag. This difference can be time.timezone
obtained by obtaining the number of seconds between the standard time zone and the local time zone. For Beijing time, this value is-28800 (8*3600). So, when we take the timestamp to 86400 (the number of seconds in a day) to get the number of seconds from 0 o'clock, there will be a difference of 8 hours. Other words
time.mktime(dateparser.parse(‘2014-09-01 09:00:00‘).timetuple()) % 86400
Will output 3600, just 8 hours from 9 o'clock in the morning.
Python Basic Time conversion