datetime

datetime是python中处理日期时间的标准库,datetime模块中常用的类包括date, time, datetime, timedelta, 使用datetime.now(),你可以用它轻松的获取当前时间, 此外可以在日期时间和字符串时间之间方便的转换。

datetime中常用的类有以下几个

  1. date, 日期对象
  2. time, 时间对象
  3. datetime , 日期时间对象
  4. timedelta, 时间间隔

1. date 类

date对象由year年份、month月份及day日期三部分构成,下面的代码获得今天的日期信息

from datetime import date

today = date.today()
print(today.year)
print(today.month)
print(today.day)

程序会依次输出今天的年份,月份,天

2. time类

time类由hour小时、minute分钟、second秒、microsecond毫秒和tzinfo五部分组成,下面的代码构建一个time对象

from datetime import time

a = time(19, 36, 30, 345)
print(a.hour)
print(a.minute)
print(a.second)
print(a.microsecond)

程序会依次输出小时,分钟,秒和毫秒

3. datetime

datetime类其实是可以看做是date类和time类的合体,也是最常使用的类,因此我们重点讲解datetime

3.1 datetime.now()

datetime.now()获取当前时间

from datetime import datetime

now = datetime.now()
print(now)
print(now.year)
print(now.month)
print(now.day)
print(now.hour)
print(now.minute)
print(now.second)
print(now.microsecond)

程序输出结果

2019-12-09 20:53:53.037121
2019
12
9
20
53
53
37121

3.2 strftime

strftime 将datetime对象转换成指定格式的字符串

from datetime import datetime

now = datetime.now()
now_str = now.strftime("%Y-%m-%d %H:%M:%S")
print(now_str)

程序输出结果

2019-12-09 20:57:04

3.3 strptime

strptime将字符串转换成datetime类型数据

from datetime import datetime

olympics_time = datetime.strptime("2008-08-08 20:08:08", '%Y-%m-%d %H:%M:%S')
print(type(olympics_time), olympics_time)

程序输出结果

<class 'datetime.datetime'> 2008-08-08 20:08:08

3.4 fromtimestamp

fromtimestamp可以将时间戳转换成datetime类型

from datetime import datetime

a = datetime.fromtimestamp(1575896495)
print(a, type(a))

4. timedelta

timedelta类可以用来计算二个datetime对象的差值

4.1 计算日期差值

from datetime import datetime

d1 = datetime(year=2019, month=12, day=9, hour=19, minute=20, second=12)
d2 = datetime(year=2019, month=12, day=7, hour=7, minute=19, second=40)

diff = d1 - d2
print(type(diff), diff)
print(diff.days, diff.seconds)

两个datetime对象做减法,可以获得相差的天数,diff.不足一天的部分换算成秒就是diff.seconds

4.2 获得上个月的第一天和最后一天

import datetime

today = datetime.datetime.now()
# 上个月最后一天
lastmonth_lastday = datetime.datetime(today.year, today.month, 1) - datetime.timedelta(1)
# 上个月第一天
lastmonth_firstday = datetime.datetime(lastmonth_lastday.year, lastmonth_lastday.month, 1)
print(lastmonth_firstday)
print(lastmonth_lastday)

4.3 当前时间向后推算8个小时

from datetime import datetime, timedelta

now = datetime.now()
eight_hours_later = now + timedelta(hours=8)
print(eight_hours_later)

扫描关注, 与我技术互动

QQ交流群: 211426309

加入知识星球, 每天收获更多精彩内容

分享日常研究的python技术和遇到的问题及解决方案