py库:time

 https://www.runoob.com/python/python-date-time.html

当前时间:

import time
now=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(int(time.time())-24*60*60))
print(now)

 

 

时间戳转换为指定日期:

# -*- coding: utf-8 -*-
#时间戳转换为指定格式日期:
import time
#timeStamp = 1381419600
timeStamp = int(time.time())     #当前时间戳
timeArray = time.localtime(timeStamp)   #本地时间
formatTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
print(formatTime)

import datetime
#获得当前时间
now = datetime.datetime.now()   #这是时间数组格式
formatTime = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatTime)

 

 

将字符串的时间转为时间戳

#将字符串的时间转换为时间戳
import time
now = "2015-11-1 23:30:00"
timeArray = time.strptime(now, "%Y-%m-%d %H:%M:%S")
timeStamp = int(time.mktime(timeArray))
print(timeStamp)

#字符串格式更改: 如now = "2015-11-01 23:30:00",想改为 now = "2015年11月01日  23:40:00"
#方法:先转换为时间数组,然后转换为其他格式
import time
now = "2015-11-01 23:30:00"
timeArray = time.strptime(now,"%Y-%m-%d %H:%M:%S")
formatTime = time.strftime("%Y/%m/%d %H:%M:%S", timeArray)
print(formatTime)

 

 

计算3天以前:

#计算3天以前
import time
import datetime
threeDayAgo = (datetime.datetime.now() - datetime.timedelta(days = 3))
timeStamp = int(time.mktime(threeDayAgo.timetuple()))
formatTime = threeDayAgo.strftime("%Y-%m-%d %H:%M:%S")
print(formatTime)

 

 

import time
# 将格式字符串转换为时间戳
b = time.mktime(time.strptime("2021-10-01 00:00:00", "%Y-%m-%d %H:%M:%S"))
# 加1天
c = time.localtime(b + 86400)
print(b)
print(c)
print(time.localtime())

# 将当前时间格式化为下列格式(2021-07-11 20:28:11)
print(time.strftime("%Y-%m-%d %H:%M:%S", c))
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

# 1633017600.0
# time.struct_time(tm_year=2021, tm_mon=10, tm_mday=2, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=275, tm_isdst=0)
# time.struct_time(tm_year=2021, tm_mon=7, tm_mday=11, tm_hour=20, tm_min=49, tm_sec=42, tm_wday=6, tm_yday=192, tm_isdst=0)
# 2021-10-02 00:00:00
# 2021-07-11 20:49:42

 

上一篇:css 基础语法


下一篇:python的time模块