Day 11:Python 时间模块


 掌握  时间戳↔时间数组↔时间字符串  的转化。

我们在写程序时可能用到记录时间的地方,例如:

  • 日志管理必然会记录时间
  • 统计程序执行开始、结束时间
  • 测试一个函数执行时长

python中与时间相关的模块:time && datetime

time模块表达时间的方法
  • 设定一个零点作为基准(初始时间),偏移长度换算为按秒的数值类型,表示时间
  • 由 9 个整数组成的元组 struct_time 表示的时间
time模块表达时间的方法
  • -data: 日期类,包括属性年、月、日及相关方法
  • -time: 时间类,时分秒
  • -datetime: 时间日期, date的子类,年月日为必要参数
  • -timedelta: 两个datetime之差,i.e. 差多少天多少小时多少分钟

P.S. 向比如说闰年判断,绘制日历,有现成模块可以调用:calendar 

import calendar
year_calerdar_str = calendar.calendar(2020)
print(year_calerdar_str)

 

 

 

import time

import time
# 1970-01-01 08:00:00 python 初始时间
# 验证初始时间
t = 0
# 时间数组 time.localtime(数)   亦称 struct_time
print(time.localtime(t))

now_time = time.time()
# 时间数组 time.localtime(数)   亦称 struct_time
print(time.localtime(now_time))
#time 类 strftime 方法,转换 struct_time 为时间 字符串
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(t)))# 数组 - > 串
init_time = time.localtime(now_time)
#time 类 asctime 方法,转换 时间数组 为时间 符串
str_time = time.asctime(init_time)
print(str_time)
# time 类 strptime 方法
format_time = time.strftime('%Y-%m-%d %H:%M:%S',init_time)
print(format_time)
# 第二个参数的时间格式,要匹配上第一个参数的时间格式。
str_to_struct = time.strptime(format_time,'%Y-%m-%d %H:%M:%S') #串->数组
str_to_struct


输出:
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=8, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)
time.struct_time(tm_year=2021, tm_mon=3, tm_mday=24, tm_hour=19, tm_min=36, tm_sec=7, tm_wday=2, tm_yday=83, tm_isdst=0)
1970-01-01 08:00:00
Wed Mar 24 19:36:07 2021
2021-03-24 19:36:07
time.struct_time(tm_year=2021, tm_mon=3, tm_mday=24, tm_hour=19, tm_min=36, tm_sec=7, tm_wday=2, tm_yday=83, tm_isdst=-1)

常用的时间格式:

%Y  年
%m   月 取值 [01,12]
%d   天 取值 [01,31]
%H   小时 取值 [00,23]
%M   分钟 取值 [00,59]
%S   秒 取值 [00,61]

import datetime 

也可以:

from datetime import date, datetime, time, timedelta

# 打印日期
Today = date.today()
print(Today, " ",type(Today))
# 日期字符串
str_today = date.strftime(Today, '%Y-%m-%d')
print(str_today, " ",type(str_today))
# 字符日期转日期  有点像(strptime )time摸块中的串类型转成数组类型日期   date类莫得,所以这样写
str_to_date = datetime.strptime('2021-03-24','%Y-%m-%d')
print(str_to_date, " ",type(str_to_date))


输出:
2021-03-24   <class 'datetime.date'>
2021-03-24   <class 'str'>
2021-03-24 00:00:00   <class 'datetime.datetime'>
关于 timedelta

两个相减的时间要一个类型  ! 年月日一定要!

def get_days_girlfriend(birthday:str)->int:
    import re
    splits = re.split(r'[-.\s+/]',birthday) # 输入时间间隔符为 - / 或者一个或多个空格
    splits = [s for s in splits if s] # 去掉空格字符
    if len(splits) < 3:
        raise ValueError('输入格式不正确,至少包括年月日') # 输入时间字符串必须包括年月日,忽略时间值。
    splits = splits[:3] # 只截取年月日
    birthday = datetime.strptime('-'.join(splits),'%Y-%m-%d')
    tod = date.today()
    delta = birthday.date() - tod
    return delta.days


print(get_days_girlfriend('2021-03-23'))
print(get_days_girlfriend('2021-03-25'))
print(date.today())


输出:
-1
1
2021-03-24

 

posted @ 2021-07-03 11:50  PiaYie  阅读(35)  评论(0编辑  收藏  举报