时间转换

date库:
获取时间戳:
timeStamp = int(time.time())
将时间戳转换为时间数组:
timeArr = time.local(timeStamp)
将时间数组转换为其他格式:
otherStyle = time.strftime(’%Y-%m-%d %H:%M:%S’,timeArr)

datetime库:
获取时间字符串:
timeString = datetime.datetime.now()
将时间戳转换为时间数组:
dateArr = datetime.datetime.utcfromtimestamp(stamp)
将时间字符串转换为其他格式:
otherStyle = dateArr.strftime(’%Y=%m=%d %H%M%S’)

"""
计算几天前并转换为指定格式。
"""
import datetime
import time

# 先获得时间数组格式的日期  三天前的时间数组
threeDayAgo = datetime.datetime.now() - datetime.timedelta(days=3)
print(threeDayAgo)
# 时间数组转换为任意指定格式
otherStyle = threeDayAgo.strftime('%Y--%m--%d %H::%M::%S')
print(otherStyle)

# 转换为时间戳
timeStamp = int(time.mktime(threeDayAgo.timetuple()))
print(timeStamp)
# 将时间戳转换为时间数组
dateArr = datetime.datetime.utcfromtimestamp(timeStamp)
print(dateArr)
"""
将时间戳转换为指定格式日期
"""
# 给定一个时间戳,将其转换为指定格式的时间。
# 首先转换为时间数组,然后将时间数组转换为指定的时间格式
import time

now = int(time.time())  # 这是一个时间戳
print(now)

timeArray = time.localtime(now)     # 时间数组
print(timeArray)

otherStyle = time.strftime('%Y-%m-%d %H:%M:%S',timeArray)   # 指定格式
print(otherStyle)

stamp = 15525235387     # 时间戳
tArr = time.localtime(stamp)
print(tArr)
oStyle = time.strftime('%Y-%m-%d %H:%M:%S',tArr)
print(oStyle)

import datetime

now = datetime.datetime.now()   # 这是一个时间字符串
print(now)

# 转换为指定格式
otherStyle = now.strftime('%Y=%m=%d %H\%M\%S')
print(otherStyle)

stamp = 15525235387     # 时间戳
# 转换为时间数组
dateArr = datetime.datetime.utcfromtimestamp(stamp)
print(dateArr)
# 将时间数组转换格式
otherStyle = dateArr.strftime('%Y=%m=%d %H\%M\%S')
print(otherStyle)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值