For time data, such as 2016-05-05 20:28:54
, sometimes need to work with the time stamp of each other operation, at this time need to convert two forms, in Python, the conversion needs to use the time
module, the specific operation is as follows:
- Convert Time to Timestamp
- Reformat time
- Time Stamp converted to time
- Get the current time and convert it to a timestamp
1. Convert Time to Timestamp
Convert the time, as above 2016-05-05 20:28:54
, into a timestamp, with the following procedure:
- Using
strptime()
functions to convert time into time arrays
- Using
mktime()
functions to convert time arrays into timestamps
#coding:UTF-8import timedt = "2016-05-05 20:28:54"#转换成时间数组timeArray = time.strptime(dt, "%Y-%m-%d %H:%M:%S")#转换成时间戳timestamp = time.mktime(timeArray)print timestamp
2. Reformat time
Reformatting time requires the following two steps:
- Using
strptime()
functions to convert time into time arrays
- Reformatting
strftime()
time with functions
#coding: Utf-8import timedt = " 2016-05-05 20:28:54 " #转换成时间数组timeArray = time.strptime (DT, Span class= "hljs-string" > "%y-%m- %d %h:%M: %s ") #转换成新的时间格式 (20160505-20:28:54) dt_new = time.strftime ( "%y%m% D-%h:%m:%S ", TimeArray)" Span class= "Hljs-keyword" >print dt_new
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
3. Convert time stamps to time
In the time stamp conversion into time, the first need to convert the timestamp to localtime, and then converted to the specific format of time:
- Using
localtime()
functions to convert timestamps into localtime formats
- Reformatting
strftime()
time with functions
#coding: Utf-8import timetimestamp = 1462451334 #转换成localtimetime_local = time. LocalTime (timestamp) #转换成新的时间格式 (2016-05-05 20:28:54) dt = Time.strftime ( "%y-%m-%d %h:%m: %s ", time_local) print dt
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
4. Get the current time in the specified format
By taking the time()
current time, the localtime()
function is converted to localtime, and finally the time is reformatted with the strftime()
function.
#coding: Utf-8import time #获取当前时间time_now = int (time. time ()) #转换成localtimetime_local = time. LocalTime (time_now) #转换成新的时间格式 (2016-05-09 18:59:20) dt = Time.strftime ( "%y-%m-%d %h:%m: %s ", time_local) print DT
turn from: http://blog.csdn.net/google19890102/article/details/ 51355282
Conversion between python-timestamp time and timestamp