Python timestamp usage and interconversion details
- 2020-06-15 09:37:10
- OfStack
This article shares the specific code of Python timestamp usage and conversion for your reference. The specific content is as follows
1. Converts the time of a string to a timestamp
Methods:
import time
a = "2013-10-10 23:40:00"
# Convert it to a time array
timeArray = time.strptime(a, "%Y-%m-%d %H:%M:%S")
# Convert to timestamp
timeStamp = int(time.mktime(timeArray))
timeStamp == 1381419600
2. String format changes
a =" 2013-10-10 23:40:00", a ="2013/10/10 23:40:00"
Method: Convert to a time array and then to another format
import time
timeArray = time.strptime(a, "%Y-%m-%d %H:%M:%S")
otherStyleTime = time.strftime("%Y/%m/%d %H:%M:%S", timeArray)
3. Time stamp converted to specified format date:
Method 1:
Convert to a time array using localtime() and format to the desired format, such as
import time
timeStamp = 1381419600
timeArray = time.localtime(timeStamp)
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
otherStyletime == "2013-10-10 23:40:00"
Method 2:
import datetime
timeStamp = 1381419600
dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
otherStyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S")
otherStyletime == "2013-10-10 23:40:00"
4. Gets the current time and converts it to the specified date format
Method 1:
import time
# Gets the current time timestamp
now = int(time.time())
# Convert to another date format , Such as :"%Y-%m-%d %H:%M:%S"
timeArray = time.localtime(timeStamp)
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
Method 2:
import datetime
# Get current time
now = datetime.datetime.now() # This is the time array format
# Converts to the specified format :
otherStyleTime = now.strftime("%Y-%m-%d %H:%M:%S")
5. Gain 3 days in advance
Methods:
import time
import datetime
# First get the date in the time array format
threeDayAgo = (datetime.datetime.now() - datetime.timedelta(days = 3))
# Convert to timestamp :
timeStamp = int(time.mktime(threeDayAgo.timetuple()))
# Convert to another string format :
otherStyleTime = threeDayAgo.strftime("%Y-%m-%d %H:%M:%S")
# note :timedelta() The parameters are :days,hours,seconds,microseconds
6. Given a timestamp, calculate the time several days before the time:
timeStamp = 1381419600
# To convert datetime
import datetime
import time
dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
threeDayAgo = dateArray - datetime.timedelta(days = 3)
# reference 5, It can be converted to any other format