Python time stamp and formatting time conversion implementation code, python
In python, time-related modules mainly include time and datetime.
If you want to obtain the current system timestamp: time. time (), it is a float data type.
Obtain the current time information of the system: time. ctime () is a str-type time string, which is generally used less
To obtain the current normal date string, you can simply use str (datetime. date. today ())
There is also the mutual conversion between time and timestamp (often used ):
Conversion from date to timestamp:
import datetimeimport timet = datetime.datetime(2014,12, 6, 12, 10, 10)timestamp = time.mktime(t.timetuple())print timestamp
Time stamp to date conversion:
import datetime import timet = time.localtime(timestamp)timeStr = time.strftime('%Y-%m-%d %H:%M:%S', t)print timeStr
A common scenario is:
Push the last few days or the next few days based on one day
For example, I need to know the data for 10 days since.
In this case, we need to perform time operations. If we follow the essence, it is the conversion between the timestamp and the time.
We can get the timestamp through time to time stamp, then perform the operation on the timestamp, and then
Convert the operation result to a time string. The complete code is as follows:
import timeimport datetimet = datetime.datetime(2014, 10, 25)timestamp = time.mktime(t.timetuple())timestamp += 10 * 3600 * 24t = time.localtime(timestamp)timeStr = time.strftime('%Y-%m-%d %H:%M:%S', t)
In fact, the date module has a function that encapsulates this algorithm, and the trial is not so big code, but let's only talk about the principle, the above python time process
In fact, it should be such a process for any language.
The language tools are constantly changing. You cannot stick to a language. Instead, you can only use algorithms and ideas.