1. Convert the time of a string to a timestamp
Method:
A = "2013-10-10 23:40:00"
Convert it to a time array
Import time
Timearray = Time.strptime (A, "%y-%m-%d%h:%m:%s")
Convert to Timestamp:
timeStamp = Int (time.mktime (Timearray))
TimeStamp = = 1381419600
2. String formatting changes
If a = "2013-10-10 23:40:00", want to change to a = "2013/10/10 23:40:00"
Method: Convert to a time array first and then to another format
Timearray = Time.strptime (A, "%y-%m-%d%h:%m:%s")
Otherstyletime = Time.strftime ("%y/%m/%d%h:%m:%s", Timearray)
3. The timestamp is converted to the specified format date:
Method One:
Use LocalTime () to convert to a time array, and then format to the desired format, such as
TimeStamp = 1381419600
Timearray = Time.localtime (TimeStamp)
Otherstyletime = Time.strftime ("%y-%m-%d%h:%m:%s", Timearray)
Otherstyletime = = "2013-10-10 23:40:00"
Method Two:
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. Get the current time and convert to the specified date format
Method One:
Import time
Get the current time time stamp
now = Int (Time.time ())--This is the timestamp
Convert to a different 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 Two:
Import datetime
Get current time
now = Datetime.datetime.now ()-This is the time array format
Convert to the specified format:
Otherstyletime = Now.strftime ("%y-%m-%d%h:%m:%s")
5. Get three days before the time
Method:
Import time
Import datetime
Gets the date of the time array format first
Threedayago = (Datetime.datetime.now ()-Datetime.timedelta (days = 3))
Convert to Timestamp:
timeStamp = Int (Time.mktime (Threedayago.timetuple ()))
Convert to a different string format:
Otherstyletime = Threedayago.strftime ("%y-%m-%d%h:%m:%s")
Note: The parameters of Timedelta () are: days,hours,seconds,microseconds
6. For a given timestamp, calculate the time of the day before:
TimeStamp = 1381419600
Convert to datetime First
Import datetime
Import time
Datearray = Datetime.datetime.utcfromtimestamp (TimeStamp)
Threedayago = Datearray-datetime.timedelta (days = 3)
Reference 5, can be converted to any other format.
Python time, date, time stamp conversion between