补齐时间格式(补充0)
ptiem = '2022-10-10'
publish_time = time.strftime("%Y-%m-%d %H:%M:%S", time.strptime(ptiem, "%Y-%m-%d"))
# publish_time 2022-10-10 00:00:00
1.将字符串的时间转换为时间戳
import time
a = "2013-10-10 23:40:00"
# 将其转换为时间数组
timeArray = time.strptime(a, "%Y-%m-%d %H:%M:%S")
print(timeArray)
# 打印结果
# time.struct_time(tm_year=2013, tm_mon=10, tm_mday=10, tm_hour=23, tm_min=40, tm_sec=0, tm_wday=3, tm_yday=283, tm_isdst=-1)
# 转换为时间戳:
timeStamp = int(time.mktime(timeArray))
print( timeStamp )
# 打印结果
# 1381419600
2.字符串格式更改
如a = “2013-10-10 23:40:00”,想改为 a = “2013/10/10 23:40:00”
方法:先转换为时间数组,然后转换为其他格式
a = "2013-10-10 23:40:00"
timeArray = time.strptime(a, "%Y-%m-%d %H:%M:%S")
otherStyleTime = time.strftime("%Y/%m/%d %H:%M:%S", timeArray)
print( otherStyleTime )
# 打印结果
# 2013/10/10 23:40:00
3.时间戳转换为指定格式日期:
方法一:
利用localtime()转换为时间数组,然后格式化为需要的格式,如
timeStamp = 1381419600
timeArray = time.localtime(timeStamp)
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
print(otherStyleTime)
# 打印结果
# 2013-10-10 23:40:00
方法二:
timeStamp = 1381419600
dateArray = datetime.utcfromtimestamp(timeStamp)
otherStyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S")
print(otherStyleTime)
# 打印结果
# 2013-10-10 23:40:00
4.获取当前时间并转换为指定日期格式
方法一:
import time
# 获得当前时间时间戳
now = int(time.time()) # 这是时间戳
# 转换为其他日期格式,如:"%Y-%m-%d %H:%M:%S"
timeArray = time.localtime(now)
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
print(now)
# 1597941570
print(otherStyleTime)
# 2020-08-21 00:39:30
方法二:
import datetime
# 获得当前时间
now = datetime.datetime.now() # 这是时间数组格式
# 转换为指定的格式:
otherStyleTime = now.strftime("%Y-%m-%d %H:%M:%S")
print(otherStyleTime)
# 2020-08-21 00:44:33
5.获得三天前的时间
import time
import datetime
# 先获得时间数组格式的日期
threeDayAgo = (datetime.datetime.now() - datetime.timedelta(days = 3))
# 转换为时间戳:
timeStamp = int(time.mktime(threeDayAgo.timetuple()))
# 转换为其他字符串格式:
otherStyleTime = threeDayAgo.strftime("%Y-%m-%d %H:%M:%S")
print(otherStyleTime)
注:timedelta()的参数有:days,hours,seconds,microseconds
6.给定时间戳,计算该时间的几天前时间:
import datetime
import time
timeStamp = 1381419600
# 先转换为datetime
dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
threeDayAgo = dateArray - datetime.timedelta(days = 3)
print(threeDayAgo)
参考5,可以转换为其他的任意格式了
计算会员过期时间
from datetime import datetime
import time
start = datetime.now() # 开通会员的起始时间
vip_time = 60 * 60 * 24 * 365 # 开通会员时长
start_s = time.mktime(start.timetuple()) # 将起始时间转换成秒
end_s = int(start_s) + vip_time # 计算会员到期时间 单位秒
timeArray = time.localtime(end_s) # 秒数
print(timeArray)
# time.struct_time(tm_year=2021, tm_mon=8, tm_mday=21, tm_hour=0, tm_min=50, tm_sec=22, tm_wday=5, tm_yday=233, tm_isdst=0)
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
print(otherStyleTime)
# 2021-08-21 00:50:22