Simple use of python's time and datetime module

Simple use of python's time and datetime module

The time module in python is mainly used to get the timestamp

for example:

import time
# 获取时间戳
# 时间戳:从时间元年(1970.1.1 00:00:00)到现在经过的秒数
print(time.time()) #1608095715.2717469

# 获取格式化事件对象
# 默认参数是当前系统时间的时间戳
print(time.gmtime())  #GMT:欧洲时区时间
# print(time.gmtime(1))  #时间元年过一秒后,对应的事件对象
print(time.localtime())  #当地时间time.struct_time(tm_year=2020, tm_mon=12, tm_mday=16, tm_hour=21, tm_min=26, tm_sec=13, tm_wday=2, tm_yday=351, tm_isdst=0)

a = time.localtime(111)
print(a) #time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=8, tm_min=1, tm_sec=51, tm_wday=3, tm_yday=1, tm_isdst=0)

# 格式化时间对象和字符串之间的转换
s = time.strftime('%Y-%m-%d %H:%M:%S') #2020-12-16 13:29:34
s1 = time.strftime('%Y %m %d') #2020 12 16
print(s)
print(s1)

# 把时间字符串转换成事件对象
time_obj = time.strptime("2020 12 16","%Y %m %d")
print(time_obj) #time.struct_time(tm_year=2020, tm_mon=12, tm_mday=16, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=351, tm_isdst=-1)



# 时间对象->时间戳
t1 = time.localtime()
t2 = time.mktime(t1)
print(t2) #1608097076.0
print(time.mktime(time.localtime())) #1608097076.0

Conversion in time:
Insert picture description here

As for the classes in the datetime module, they are mainly used for mathematical calculations, for example:

# date类:
import datetime
d = datetime.date(2010,10,10)
print(d) #2010-10-10
# 获取date对象的各个属性
print(d.year) #2010
print(d.month) #10
print(d.day) #10

# time类
t = datetime.time(10,48,59)
print(t) #10:48:59
# time类的属性
print(t.hour) #10
print(t.minute) #48
print(t.second) #59

# datetime类
dt = datetime.datetime(2010,11,11,11,11,11)
print(dt) #2010-11-11 11:11:11

# datetime中的类,主要是用于数学计算
# timedelta:时间的变化量
# 只能和以下三类进行数学运算:date,datetime,timedaelta

td = datetime.timedelta(days=1)
dt = datetime.date(2020,10,10)
res = d + td
print(res) #2010-10-11

# 时间变化量的计算是否会产生进位?
t = datetime.datetime(2010,10,10,10,10,59) #如果是datetime.time(10,10,10)则会报错
td = datetime.timedelta(seconds=3)
res = t + td
res1 = t - td
print(res) #2010-10-10 10:11:02
print(res1) #2010-10-10 10:10:56

Here is a small exercise:
Calculate how many days are in February in a certain year
Ordinary algorithm: Calculate whether it is a leap year based on the year, yes: 29 days, no: 28
Use the datetime module to
prompt: first create March 1 of the specified year, and then Let it go one day forward to get the number of days in the month

answer:

year = int(input("输入年份:"))
d = datetime.date(year,3,1)
td = datetime.timedelta(days = 1)
res = d -td
print(res.day)

# 或者:
d = datetime.date(2010,3,1)
td = datetime.timedelta(days=1)
res = d - td
print(res)

The above is a summary of the study based on the 22nd episode of the full stack video of the old boy on Bilibili~
I think this article is useful to you, please give the author a little support~ Your encouragement is a great motivation for me to move forward!

Guess you like

Origin blog.csdn.net/m0_50481455/article/details/111273886