Home > Article > Backend Development > What is the method for converting python timestamp to date format?
The conversion of date and time can be completed using Python's built-in modules time and datetime, and there are many methods for us to choose from. Of course, we can directly use the current time or specified characters when converting Time format in string format.
Get the current time conversion
We can use the built-in module datetime to get the current time and then convert it to the corresponding timestamp.
import datetime import time # 获取当前时间 dtime = datetime.datetime.now() un_time = time.mktime(dtime.timetuple()) print(un_time) # 将unix时间戳转换为“当前时间”格式 times = datetime.datetime.fromtimestamp(un_time) print(times)
Conversion result:
1559568302.0 2019-06-03 21:25:02
Conversion of string time
Of course we can also directly convert the string type The timestamp corresponding to the time.
import datetime import time # 字符类型的时间 tss1 = '2019-06-03 21:19:03' # 转为时间数组 timeArray = time.strptime(tss1, "%Y-%m-%d %H:%M:%S") print(timeArray) # timeArray可以调用tm_year等 print(timeArray.tm_year) # 2019 # 转为时间戳 timeStamp = int(time.mktime(timeArray)) print(timeStamp) # 1559567943
Example results:
time.struct_time(tm_year=2019, tm_mon=6, tm_mday=3, tm_hour=21, tm_min=19, tm_sec=3, tm_wday=0, tm_yday=154, tm_isdst=-1) 2019 1559567943
Other methods of converting timestamp to date
localtime
We can use localtime() to convert to a time array, and then format it into the required format
import time timeStamp = 1559567943 timeArray = time.localtime(timeStamp) otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray) print(otherStyleTime)
Example result:
2019-06-03 21:19:03
utcfromtimestamp
import time import datetime timeStamp = 1559567943 dateArray = datetime.datetime.utcfromtimestamp(timeStamp) otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray) print(otherStyleTime)
python learning network, a large number of free python video tutorials, welcome to learn online!
The above is the detailed content of What is the method for converting python timestamp to date format?. For more information, please follow other related articles on the PHP Chinese website!