Time模块

  • time模块基于Unix Timestamp。
  • datetime模块基于time进行了封装,提供更多函数。

这两个模块都处理事件,但是对于时间的封装却不同

  • time模块提供struct_time类, 即(time tuple, p_tuple, 时间元组)
  • datetime模块常用datetime和timedelta类,也提供了date、time类

python中时间分为

类型 所属
时间戳 time模块,datetime模块
时间元组struct_time time模块
datetime对象 datetime模块(又包含date对象和time对象)
timedelta对象 datetime模块

time模块中时间表现格式

time模块中时间表现的格式主要有三种:

  • timestamp时间戳,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量
  • struct_time时间元组,共有九个元素组。
  • format time 格式化时间,已格式化的结构使时间更具可读性。包括自定义格式和固定格式。

img

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import time

# 获取struct_time
p_tuple = time.localtime()
print(p_tuple) # time.struct_time(tm_year=2019, tm_mon=8, tm_mday=6, tm_hour=9, tm_min=30, tm_sec=58, tm_wday=1, tm_yday=218, tm_isdst=0)


# 获取时间戳(当前时间)
print(time.time()) # 1565055058.6990192
# 获取时间戳(传入时间元组)
print(time.mktime(p_tuple)) # 1565055058.0


# 获取时间字符串(接受时间元组)
print(time.asctime(p_tuple)) # Tue Aug 6 09:32:37 2019
# 获取时间字符串(接受时间戳)
print(time.ctime(time.time())) # Tue Aug 6 09:32:37 2019


# 时间格式化(时间元组转为时间字符串)
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
# 时间格式化(时间字符串转为时间元组)
s = '2016-08-25 16:30:58'
print(time.strptime(s, "%Y-%m-%d %H:%M:%S"))

datetime模块

datetime模块中包含类

类名 功能说明
date 日期对象,常用的属性有year, month, day
time 时间对象
datetime 日期时间对象,常用的属性有hour, minute, second, microsecond
timedelta 时间间隔,即两个时间点之间的长度
tzinfo 时区信息对象
datetime_CAPI 日期时间对象C语言接口

date对象

date对象由year年份、month月份及day日期三部分构成:

1
date(year,month,day)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import datetime

# 获取date对象(今天)
x = datetime.date.today()
# 获取date对象(传入日期)
a = datetime.date(2017,3,1)


print(x) # 2019-08-06
print(x.year) # 2019
print(x.month) # 8
print(x.day) # 6

print(x.strftime('%Y-%m-%d')) # 2019-08-06

# 转化为time模块的struct_time对象
print(x.timetuple())

注意datetime的replace函数,可以直接替换日期.

1
2
3
4
5
6
7
import datetime 

day1 = datetime.datetime.now()
day2 = day1.replace(year=2018,day=12)

print(day1) # 2019-08-10 09:33:56.048926
print(day2) # 2018-08-12 09:33:56.048926

time对象

time类由hour小时、minute分钟、second秒、microsecond毫秒和tzinfo五部分组成

1
time([hour[, minute[, second[, microsecond[, tzinfo]]]]])
1
2
3
4
5
6
7
8
9
10
import datetime

x = datetime.time(12,20,59,889)
print(x) # 12:20:59.000889
print(x.hour) # 12
print(x.minute) # 20
print(x.second) # 59
print(x.microsecond) # 889

print(x.strftime('%H:%M:%S')) # 12:20:59

datetime类

datetime类其实是可以看做是date类和time类的合体,其大部分的方法和属性都继承于这二个类

1
datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import datetime

# 获取datetime对象(现在)
a = datetime.datetime.now()
# 获取datetime对象(传入参数)
x = datetime.datetime(2017, 3, 22, 16, 9, 33, 494248)
print(x) # 2017-03-22 16:09:33.494248

# 转为time对象和date对象
print(x.date()) # 2017-03-22
print(x.time()) # 16:09:33.494248

print(type(x.date())) # <class 'datetime.date'>
print(type(x.time())) # <class 'datetime.time'>

# 将time对象和date对象合并为datetime对象
a = datetime.datetime.now()
x = datetime.datetime.combine(a.date(),a.time())
print(x) # 2019-08-06 10:02:07.379849

# 字符串格式化
x = datetime.datetime.strptime('2017-3-22 15:25','%Y-%m-%d %H:%M')
print(x) # 2017-03-22 15:25:00

timedelta类

timedelta类是用来计算二个datetime对象的差值的。

此类中包含如下属性:

  • days : 天数
  • microseconds :微秒数(>=0 并且 <1秒)
  • seconds :秒数(>=0 并且 <1天)

实操

获取当前日期时间

1
2
3
4
5
6
7
8
9
10
11
import datetime

# 注意datetime.time没有now函数
# 需要从datetime.datetime对象使用time()函数转化
now = datetime.datetime.now()
today = datetime.date.today()

print(now,today)
# 2019-08-06 10:07:39.114380 2019-08-06

print(now.time()) # 10:08:47.743319

获取上个月第一天和最后一天的日期

1
2
3
4
5
6
7
8
9
10
11
12
import datetime

today = datetime.date.today()
print(today) # 2019-08-06

# 上个月最后一天 : 这个月的第一天减去1天
last_day = datetime.date(today.year,today.month,1) - datetime.timedelta(1)
print(last_day) # 2019-07-31

# 上个月第一天 : last_day的日期改为1就行了
first_day = datetime.date(last_day.year,last_day.month,1)
print(first_day) # 2019-07-01

获取时间差

1
2
3
4
5
6
7
8
9
10
11
import datetime

x = datetime.datetime(2017, 3, 22, 16, 9, 33, 494248)
y = datetime.datetime(2014, 2, 23, 12, 19, 24, 49448)

z = x - y
print(type(z)) # <class 'datetime.timedelta'>
print(z) # 1123 days, 3:50:09.444800
# 注意加s
print(z.seconds) # 13809
print(z.days) # 1123

计算当前时间向后8个小时的时间

1
2
3
4
5
6
import datetime

now = datetime.datetime.now()
x = datetime.timedelta(hours=8)

print(now + x) # 2019-08-06 18:41:25.964167

计算上周一和周日的日期

1
2
3
4
5
6
7
8
9
10
11
12
13
#  计算上周一和周日的日期
import datetime

today = datetime.datetime.today()
print(today) # 2019-08-06 10:44:47.022135

today_weekday = today.isoweekday()
last_sunday = today - datetime.timedelta(days=today_weekday)
last_monday = last_sunday - datetime.timedelta(days=6)

print(today_weekday) # 2
print(last_sunday) # 2019-08-04 10:44:47.022135
print(last_monday) # 2019-07-29 10:44:47.022135

计算指定日期当月最后一天的日期和本月天数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 计算指定日期当月最后一天的日期和本月天数
import datetime

x = datetime.date(2017,12,20)
print(x) # 2017-12-20

if x.month == 12:
last_day = datetime.date(x.year+1,1,1) - datetime.timedelta(days=1)
else:
last_day = datetime.date(x.year,x.month+1,1) - datetime.timedelta(days=1)

print(last_day) # 2017-12-31

# 最后一天就是这个月的天数
day_num = last_day.day
print(day_num) # 31

计算指定日期下个月当天的日期

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import datetime

date = datetime.date(2017,1,30)

def eomonth(day):
'''获取本月最后一天的日期'''
if day.month == 12:
last_day = datetime.date(day.year+1,1,1) - datetime.timedelta(days=1)
else:
last_day = datetime.date(day.year,day.month+1,1) - datetime.timedelta(days=1)
return last_day

def edate(date_object):
'''计算指定日期下个月当天的日期'''
if date_object.month == 12:
next_month_date = datetime.date(date_object.year+1, 1,date_object.day)
else:
next_month_first_day = datetime.date(date_object.year,date_object.month+1,1)
# 指定日期的天数 大于 下一个月的天数
if date_object.day > eomonth(next_month_first_day).day:
# 下一个月的最后一天
next_month_date = datetime.date(date_object.year,date_object.month+1,eomonth(next_month_first_day).day)
else:
next_month_date = datetime.date(date_object.year, date_object.month+1, date_object.day)
return next_month_date

print(edate(date)) # 2017-02-28

获得本周一至今天的时间段并获得上周对应同一时间段

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#  获得本周一至今天的时间段并获得上周对应同一时间段
import datetime

today = datetime.datetime.now()

this_monday = today - datetime.timedelta(days=today.isoweekday()-1)
this_monday = datetime.datetime(this_monday.year,this_monday.month,this_monday.day)

last_monday = this_monday - datetime.timedelta(days=7)
last_weekday = today - datetime.timedelta(7)

day_diff = today - this_monday

print(last_monday) # 2019-07-29 00:00:00
print(last_weekday) # 2019-07-30 11:15:47.839859
print(day_diff) # 1 day, 11:15:47.839859

calendar模块

  1. calendar.Calendar(firstweekday=0)
    该类提供了许多生成器,如星期的生成器,某月日历生成器
  2. calendar.TextCalendar(firstweekday=0)
    该类提供了按月、按年生成日历字符串的方法。
  3. calendar.HTMLCalendar(firstweekday=0)
    类似TextCalendar,不过生成的是HTML格式日历

函数及描述

  1. calendar.calendar(year, w=2, l=1, c=6, m=3)
    返回一个多行字符串格式的year年年历。

  2. calendar.firstweekday()
    返回当前每周起始日期的设置。默认返回0,即星期一。

  3. calendar.isleap(year)
    闰年返回True,否则False。

  4. calendar.leapdays(y1, y2)
    返回y1到y2之间的闰年总数,包含y1,不包含y2。

  5. calendar.month(year, month, w=2, l=1)
    返回一个多行字符串格式的year年month月日历。

  6. calendar.monthcalendar(year,month)
    返回一个整数的单层嵌套列表。每个子列表装载一个星期。该月之外的日期都为0,该月之内的日期设为该日的日期,从1开始。

  7. calendar.monthrange(year, month)
    返回两个整数组成的元组,第一个是该月的第一天是星期几,第二个是该月的天数。(calendar.monthrange(year, month):

此处计算星期几是按照星期一为0计算。

  1. calendar.prcal(year, w=2, l=1, c=6)
    等于print calendar.calendar(year)

  2. calendar.prmonth(year, month)
    同上。

  3. calendar.setfirstweekday(weekday)
    设置每周起始日期码。0(星期一)到6(星期日)

  4. calendar.timegm(tupletime)
    和time.gmtime相反,接收一个时间元组,返回该时刻的时间戳(计算机元年之后的秒数)

  5. calendar.weekday(year, month, day)
    返回给定日期的星期码,0(星期一)到6(星期日)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import calendar

# 指定年月的日历
print(calendar.month(2018, 10))
# 指定年的日历
print(calendar.calendar(2016))
# 某年是否为闰年
print(calendar.isleap(2012)) # True
# 在Y1,Y2两年之间的闰年总数。
print(calendar.leapdays(y1=2007,y2=2013))
# 某个月的星期序列
print(calendar.monthcalendar(2019, 8))
# [[0, 0, 0, 1, 2, 3, 4], [5, 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17, 18], [19, 20, 21, 22, 23, 24, 25], [26, 27, 28, 29, 30, 31, 0]]

# 第一个是该月的第一天是星期几(从0算起:3表示星期四),第二个是该月的天数。
print(calendar.monthrange(2019,8)) # (3, 31)
# 返回星期几(从0算起:5表示星期六)
print(calendar.weekday(year=2019, month=8, day=10)) # 5