常见模块-datetime模块

datetime
说明
date 日期
time 时间
datetime 日期+时间
timedelta 两个时间间隔,可达微秒

1、datetime模块-date类

import datetime

date11=datetime.date(2022,1,18)
print(date11)#2022-01-18
print(date11.year)#2022
print(date11.month)#1
print(date11.day)#18

today=datetime.date.today()
print(today)#2022-01-18

print(today

2、datetime模块-time类

import datetime

time=datetime.time(12,6,9)
print(time.hour)#12
print(time.minute)#6
print(time.second)#9

print(time.isoformat())#12:06:09
print(time.strftime("%H %M %S"))#12 06 09

3、datetime模块-datetime类

class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
import datetime

#返回datetime对象
datetime_c=datetime.datetime.today()#2022-01-18 18:40:41.694379

#返回datetime对象
datetime_c1=datetime.datetime.now()#指定zk时区,否则同上

#返回datetime对象
datetime_c2=datetime.datetime.utcnow()#返回utc区的datetime对象

#将时间戳转换为datetime对象
datetime_c3=datetime.datetime.fromtimestamp(3600*24)#1970-01-02 08:00:00

#将时间戳转换为datetime对象
datetime_c4=datetime.datetime.utcfromtimestamp(3600*24)#1970-01-02 00:00:00


#将时间字符串转换为datetime对象
datetime_c5=datetime.datetime.strptime("2021-10-12","%Y-%m-%d")#2021-10-12 00:00:00
print(datetime_c5)

 #以上返回的都是datetime对象

import datetime

#返回datetime对象
dt_c=datetime.datetime.today()#2022-01-18 18:40:41.694379
print(dt_c.year)#2022
print(dt_c.month)#1
print(dt_c.day)#18

print(dt_c.hour)#19
print(dt_c.minute)#7
print(dt_c.second)#31

print(dt_c.date)#返回date对象
print(dt_c.time)#返回time对象
print(dt_c.isoformat())#2022-01-18T19:10:56.114325
print(dt_c.strftime("%Y-%m-%d"))#2022-01-18

4、datetime模块-timedelta类

class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, hours=0, weeks=0)
import datetime

now=datetime.datetime.now()

# 计算此刻三天前的时间对象
delta = datetime.timedelta(days=3)

before_3day = now - delta

print(before_3day)#2022-01-15 19:16:14.295565

你可能感兴趣的:(python,python,开发语言,后端)