datetime模块用法
前言
datetime是Python处理日期和时间的标准库。
用法
-
datetime.now():获取当前的日期和时间
-
datetime.now().date():返回当前日期
-
datetime.now().time():返回当前时间
-
datetime.tzinfo: 与时区的相关信息
-
datetime.date
一个理想化的简单型日期,它假设当今的公历在过去和未来永远有效。 属性: year, month, and day。
a=date(2001,1,1)
year = a.year #year=2001
-
datetime.datetime
日期和时间的结合。属性:year, month, day, hour, minute, second, microsecond, and tzinfo -
datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
可用于时间的加减
所有参数都是可选的并且默认为 0。 这些参数可以是整数或者浮点数,也可以是正数或者负数。
例题(十二届蓝桥杯Python组国赛C题)
from datetime import *
from math import *
a = date(2001, 1, 1) # 起始日期
b = date(2021, 12, 31) # 终止日期
gap = timedelta(days=1)
# 计算每个位数的和
def cul(n):
sum_ = 0
strn = str(n)
for i in strn:
sum_ += int(i)
return sum_
# 判断是否为完全平方数
def isSquare(n):
x = sqrt(n)
y = int(sqrt(n))
if x == y:
return True
else:
return False
ans = 0
while a != b:
year = a.year
month = a.month
day = a.day
sum0 = cul(year) + cul(month) + cul(day)
if isSquare(sum0):
ans += 1
print('a:', a)
a += gap
print('天数:', ans)