Realization of pandas Time Format Conversion
- 2021-07-10 20:05:02
- OfStack
OUTLINE
Common conversions between time strings and timestamp
Conversion between date and timestamp
Common conversions between time strings and timestamp
The string mentioned here is not a string in the general sense, which means that when reading date-type data, if the string has not been parsed in time, it is not a date-type, so how can the string be converted with the timestamp at this time?
(1) Converting Time String into Time Stamp Converting Time String into Time Stamp is divided into two steps:
Step 1: Convert a time string to a time tuple
Step 2: Convert time tuples to timestamp types
import time
data['timestamp'] = data['OCC_TIM'].apply(lambda x:time.mktime(time.strptime(x,'%Y-%m-%d %H:%M:%S')))
Among them, the strptime function converts the string into a time tuple type according to the following format; The mktime function converts time tuples into timestamps. Remember these two commonly used functions.
② Convert timestamps into readable strings
Step 1: Convert the timestamp with localtime to local_time, time tuple
Step 2: Convert local_time to a readable string with strftime
timestamp = 1.521708e+09
time_local = time.localtime(timestamp)
time_local
# Output:
# time.struct_time(tm_year=2018, tm_mon=3, tm_mday=22, tm_hour=16, tm_min=40, tm_sec=0, tm_wday=3, tm_yday=81, tm_isdst=0)
time.strftime('%Y/%m/%d %H:%M:%S',time_local)
# Output:
# '2018/03/22 16:40:00'
Conversion between date and timestamp
However, if you have used the parameter parse_dates when reading the data, the readable string is replaced by the date format. How to convert the date to timestamp?
So what we should think about is how to convert dates into time tuples!
import time
data['timestamp'] = data['OCC_TIM'].apply(lambda x:time.mktime(x.timetuple())) # So the most important thing is Date .timetuple() This usage It converts dates into time tuples
data.head(10)