Python3日期与时间戳转换的几种方法

14035218-da8f0d185852b2eb.jpg
175.jpg

Outline

Conversion date and time of the built-in module may utilize Python timeand datetimecomplete, and there are various methods for our choice, of course, we can directly use when converting the current time or a specified time format string format.

Get the current time conversion

We can use the built-in module datetimeacquires the current time, and then convert it to the corresponding time stamp.

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 results:

1559568302.0
2019-06-03 21:25:02

Time string conversion

Of course, we can directly type string corresponding to the time stamp.

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

Sample 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 timestamp of the date of transfer

localtime

We can use localtime () is converted to an array of time, then formatted into the required format

import time
timeStamp = 1559567943
timeArray = time.localtime(timeStamp)
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
print(otherStyleTime)

Sample results:

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)

Guess you like

Origin blog.csdn.net/weixin_34357436/article/details/90945501