Wednesday
weekday(): 2
isoweekday() 3
Friday
weekday(): 4
isoweekday() 5
8计算两个日期时间对象之间的时差
import datetime
from datetime import timedelta
datetimeFormat = ‘%Y-%m-%d %H:%M:%S.%f’
date1 = ‘2016-04-16 10:01:28.585’
date2 = ‘2016-03-10 09:56:28.067’
diff = datetime.datetime.strptime(date1, datetimeFormat)\
- datetime.datetime.strptime(date2, datetimeFormat)
print(“Difference:”, diff)
print(“Days:”, diff.days)
print(“Microseconds:”, diff.microseconds)
print(“Seconds:”, diff.seconds)
Output:
Difference: 37 days, 0:05:00.518000
Days: 37
Microseconds: 518000
Seconds: 300
9将 5 分钟添加到 Unix 时间戳
import datetime
import calendar
future = datetime.datetime.utcnow() + datetime.timedelta(minutes=5)
print(calendar.timegm(future.timetuple()))
Output:
1621069619
10在 Python 中遍历一系列日期
import datetime
start = datetime.datetime.strptime(“21-06-2020”, “%d-%m-%Y”)
end = datetime.datetime.strptime(“05-07-2020”, “%d-%m-%Y”)
date_generated = [start + datetime.timedelta(days=x) for x in range(0, (end - start).days)]
for date in date_generated:
print(date.strftime(“%d-%m-%Y”))
Output:
21-06-2020
22-06-2020
23-06-2020
24-06-2020
25-06-2020
26-06-2020
27-06-2020
28-06-2020
29-06-2020
30-06-2020
01-07-2020
02-07-2020
03-07-2020
04-07-2020
11巴黎时间更改为纽约时间
import pendulum
in_paris = pendulum.datetime(2016, 8, 7, 22, 24, 30, tz=‘Europe/Paris’)
print(in_paris)
in_us = in_paris.in_timezone(‘America/New_York’)
print(in_us)
Output:
2016-08-07T22:24:30+02:00
2016-08-07T16:24:30-04:00
12使用 Python 获得最后7个工作日
from datetime import date
from datetime import timedelta
today = date.today()
for i in range(7):
d = today - timedelta(days=i)
if d.weekday() < 5:
print(d)
Output:
2021-05-18
2021-05-17
2021-05-14
2021-05-13
2021-05-12
13从今天的日期和一个人的生日推算年龄
from datetime import date
def calculate_age(born):
today = date.today()
try:
birthday = born.replace(year=today.year)
except ValueError:
birthday = born.replace(year=today.year, month=born.month + 1, day=1)
if birthday > today:
return today.year - born.year - 1
else:
return today.year - born.year
print(calculate_age(date(2001, 3, 1)))
Output:
20
14获得本月的第一个星期二
import calendar
from datetime import datetime
c = calendar.Calendar(firstweekday=calendar.SUNDAY)
monthcal = c.monthdatescalendar(datetime.today().year, datetime.today().month)
try:
tues = [day for week in monthcal for day in week if
day.weekday() == calendar.TUESDAY and day.month == datetime.today().month][0]
print(tues)
except IndexError:
print(‘No date found’)
Output:
2021-05-04
15将整数转换为日期对象
from datetime import datetime
i = 1545730073
timestamp = datetime.fromtimestamp(i)
print(timestamp)
print(type(timestamp))
Output:
2018-12-25 14:57:53
16当前日期减去 N 天的天数
from datetime import datetime, timedelta
d = datetime.today() - timedelta(days=5)
print(d)
Output:
2021-05-10 12:59:14.867969
17比较两个日期
import datetime
a = datetime.datetime(2020, 12, 31, 23, 59, 59)
b = datetime.datetime(2020, 11, 30, 23, 59, 59)
print(a < b)
print(a > b)
Output:
False
True
18从 datetime 对象中提取年份
import datetime
year = datetime.date.today().year
print(year)
Output:
2021
19在 Python 中找到星期几
import pendulum
dt = pendulum.parse(‘2021-05-18’)
print(dt.day_of_week)
dt = pendulum.parse(‘2021-05-01’)
print(dt.day_of_week)
dt = pendulum.parse(‘2021-05-21’)
print(dt.day_of_week)
Output:
2
6
5
20从当前日期获取 7 天前的日期
from datetime import datetime, timedelta
now = datetime.now()
for x in range(7):
d = now - timedelta(days=x)
print(d.strftime(“%Y-%m-%d”))
Output:
2021-05-18
2021-05-17
2021-05-16
2021-05-15
2021-05-14
2021-05-13
2021-05-12
21将两个日期时间对象之间的差值转换为秒
import datetime
time1 = datetime.datetime.strptime(‘19 01 2021’, ‘%d %m %Y’)
time2 = datetime.datetime.strptime(‘25 01 2021’, ‘%d %m %Y’)
difference = time2 - time1
print(difference)
seconds = difference.total_seconds()
print(seconds)
Output:
6 days, 0:00:00
518400.0
22获得任何一个月的第三个星期五
import calendar
c = calendar.Calendar(firstweekday=calendar.SUNDAY)
year = 2021
month = 5
monthcal = c.monthdatescalendar(year, month)
try:
third_friday = [day for week in monthcal for day in week if
day.weekday() == calendar.FRIDAY and day.month == month][2]
print(third_friday)
except IndexError:
print(‘No date found’)
Output:
2021-05-21
23从 Python 中的周数获取日期
import datetime
from dateutil.relativedelta import relativedelta
week = 25
year = 2021
date = datetime.date(year, 1, 1) + relativedelta(weeks=+week)
print(date)
Output:
2021-06-25
24获取特定日期的工作日
import datetime
print(datetime.date(2020, 5, 15).isocalendar()[2])
Output:
5
25创建一个 15 分钟前的 DateTime
import datetime
dt = datetime.datetime.now() - datetime.timedelta(minutes=15)
print(dt)
Output:
2021-05-15 22:25:55.897365
26从特定日期获取周的开始和结束日期
import pendulum
dt = pendulum.datetime(2012, 9, 5)
start = dt.start_of(‘week’)
print(start.to_datetime_string())
end = dt.end_of(‘week’)
print(end.to_datetime_string())
Output:
2012-09-03 00:00:00
2012-09-09 23:59:59
27两个日期之间的差异(以秒为单位)
from datetime import datetime
fmt = ‘%Y-%m-%d %H:%M:%S’
d1 = datetime.strptime(‘2020-01-01 17:31:22’, fmt)
d2 = datetime.strptime(‘2020-01-03 17:31:22’, fmt)
days_diff = d2 - d1
print(days_diff.days * 24 * 60 * 60)
Output:
172800
28以这种格式获取昨天的日期MMDDYY
from datetime import date, timedelta
yesterday = date.today() - timedelta(days=1)
print(yesterday.strftime(‘%m%d%y’))
Output:
051421
29从今天的日期获取上周三
from datetime import date
from datetime import timedelta
today = date.today()
offset = (today.weekday() - 2) % 7
wednesday = today - timedelta(days=offset)
print(wednesday)
Output:
2021-05-12
30所有可用时区的列表打印
import pytz
for i in pytz.all_timezones:
print(i)
Output:
Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
Africa/Algiers
Africa/Asmara
Africa/Asmera
Africa/Bamako
Africa/Bangui
Africa/Banjul
Africa/Bissau
…
US/Mountain
US/Pacific
US/Samoa
UTC
Universal
W-SU
WET
Zulu
31获取指定开始日期和结束日期之间的日期范围
import datetime
start = datetime.datetime.strptime(“21-06-2020”, “%d-%m-%Y”)
end = datetime.datetime.strptime(“05-07-2020”, “%d-%m-%Y”)
date_generated = [start + datetime.timedelta(days=x) for x in range(0, (end - start).days)]
for date in date_generated:
print(date.strftime(“%d-%m-%Y”))
Output:
21-06-2020
22-06-2020
23-06-2020
24-06-2020
25-06-2020
26-06-2020
27-06-2020
28-06-2020
29-06-2020
30-06-2020
01-07-2020
02-07-2020
03-07-2020
04-07-2020
32毫秒转换为数据
import datetime
time_in_millis = 1596542285000
dt = datetime.datetime.fromtimestamp(time_in_millis / 1000.0, tz=datetime.timezone.utc)
print(dt)
Output:
2020-08-04 11:58:05+00:00
33查找给定日期之后的第一个星期日的日期
import datetime
def next_weekday(d, weekday):
days_ahead = weekday - d.weekday()
if days_ahead <= 0:
days_ahead += 7
return d + datetime.timedelta(days_ahead)
d = datetime.date(2021, 5, 16)
next_sunday = next_weekday(d, 6)
print(next_sunday)
Output:
2021-05-23
34将(Unix)时间戳秒转换为日期和时间字符串
from datetime import datetime
dateStr = datetime.fromtimestamp(1415419007).strftime(“%A, %B %d, %Y %I:%M:%S”)
print(type(dateStr))
print(dateStr)
Output:
Saturday, November 08, 2014 09:26:47
35以月为单位的两个日期之间的差异
from datetime import datetime
from dateutil import relativedelta
date1 = datetime.strptime(‘2014-01-12 12:00:00’, ‘%Y-%m-%d %H:%M:%S’)
date2 = datetime.strptime(‘2021-07-15 12:00:00’, ‘%Y-%m-%d %H:%M:%S’)
r = relativedelta.relativedelta(date2, date1)
print(r.months + (12 * r.years))
Output:
90
36将本地时间字符串转换为 UTC
from datetime import *
from dateutil import *
from dateutil.tz import *
utc_zone = tz.gettz(‘UTC’)
local_zone = tz.gettz(‘America/Chicago’)
utc_zone = tz.tzutc()
local_zone = tz.tzlocal()
local_time = datetime.strptime(“2020-10-25 15:12:00”, ‘%Y-%m-%d %H:%M:%S’)
print(local_time)
local_time = local_time.replace(tzinfo=local_zone)
print(local_time)
utc_time = local_time.astimezone(utc_zone)
print(utc_time)
utc_string = utc_time.strftime(‘%Y-%m-%d %H:%M:%S’)
print(utc_string)
Output:
2020-10-25 15:12:00
2020-10-25 15:12:00+05:30
2020-10-25 09:42:00+00:00
2020-10-25 09:42:00
37获取当月的最后一个星期四
import calendar
from datetime import datetime
month = calendar.monthcalendar(datetime.today().year, datetime.today().month)
thrusday = max(month[-1][calendar.THURSDAY], month[-2][calendar.THURSDAY])
print(thrusday)
Output:
27
38从特定日期查找一年中的第几周
import pendulum
dt = pendulum.parse(‘2015-05-18’)
print(dt.week_of_year)
dt = pendulum.parse(‘2019-12-01’)
print(dt.week_of_year)
dt = pendulum.parse(‘2018-01-21’)
print(dt.week_of_year)
Output:
21
48
3
39从给定日期获取星期几
import datetime
import calendar
dt = datetime.datetime(2021, 4, 25, 23, 24, 55, 173504)
print(calendar.day_name[dt.weekday()])
Output:
Sunday
40用 AM PM 打印当前时间
from datetime import datetime
print(datetime.today().strftime(“%I:%M %p”))
Output:
10:11 PM
41获得一个月的最后一天
import calendar
print(calendar.monthrange(2002, 1)[1])
print(calendar.monthrange(2008, 6)[1])
print(calendar.monthrange(2012, 2)[1])
print(calendar.monthrange(2015, 2)[1])
Output:
31
30
29
28
42从工作日值中获取工作日名称
import calendar
print(calendar.day_name[0])
print(calendar.day_name[1])
print(calendar.day_name[2])
print(calendar.day_name[3])
print(calendar.day_name[4])
print(calendar.day_name[5])
print(calendar.day_name[6])
Output:
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
43将 N 小时数添加到当前日期时间
from datetime import datetime, timedelta
d = datetime.today() + timedelta(hours=18)
print(d)
Output:
2021-05-16 07:36:08.189948
44从当前日期获取年、月、日、小时、分钟
import datetime
now = datetime.datetime.now()
print(now.year, now.month, now.day, now.hour, now.minute, now.second)
Output:
2021 5 15 14 27 33
45获取特定月份和年份的最后一个星期日
import calendar
month = calendar.monthcalendar(2021, 2)
last_sunday = max(month[-1][calendar.SUNDAY], month[-2][calendar.SUNDAY])
print(last_sunday)
Output:
28
46查找特定日期的年份中的哪一天
import pendulum
dt = pendulum.parse(‘2015-05-18’)
print(dt.day_of_year)
dt = pendulum.parse(‘2019-12-01’)
print(dt.day_of_year)
dt = pendulum.parse(‘2018-01-21’)
print(dt.day_of_year)
Output:
138
335
21
47查找当前日期是工作日还是周末
import datetime
weekno = datetime.datetime.today().weekday()
if weekno < 5:
print(“Weekday”)
else: # 5 Sat, 6 Sun
print(“Weekend”)
Output:
Weekday
48组合 datetime.date 和 datetime.time 对象
import datetime
d = datetime.datetime.combine(datetime.date(2020, 11, 14),
datetime.time(10, 23, 15))
print(d)
Output:
2020-11-14 10:23:15
49获得每月的第 5 个星期一
import calendar
c = calendar.Calendar(firstweekday=calendar.SUNDAY)
year = 2016
month = 2
monthcal = c.monthdatescalendar(year, month)
try:
fifth_monday = [day for week in monthcal for day in week if
day.weekday() == calendar.MONDAY and day.month == month][4]
print(fifth_monday)
except IndexError:
print(‘No date found’)
Output:
2016-02-29
50将日期时间对象转换为日期对象
from datetime import datetime
datetime_obj = datetime(2020, 12, 15, 10, 15, 45, 321474)
print(datetime_obj)
date_obj = datetime_obj.date()
print(date_obj)
Output:
2020-12-15 10:15:45.321474
2020-12-15
51获取没有微秒的当前日期时间
from datetime import datetime
print(datetime.now().isoformat(’ ', ‘seconds’))
Output:
2021-05-15 12:55:45
52将 N 秒数添加到特定日期时间
import datetime
a = datetime.datetime(2020, 12, 31, 23, 59, 45)
b = a + datetime.timedelta(seconds=30)
print(a)
print(b)
Output:
2020-12-31 23:59:45
2021-01-01 00:00:15
53从当前日期获取两位数的月份和日期
import datetime
dt = datetime.datetime.now()
print(dt.strftime(‘%m’))
print(‘{:02d}’.format(dt.month))
print(f’{dt.month:02d}')
print(‘%02d’ % dt.month)
print(dt.strftime(‘%d’))
print(‘{:02d}’.format(dt.day))
print(f’{dt.day:02d}')
print(‘%02d’ % dt.day)
Output:
05
05
05
05
15
15
15
15
54从特定日期获取月份数据的开始和结束日期
import pendulum
dt = pendulum.datetime(2012, 9, 5)
start = dt.start_of(‘month’)
print(start.to_datetime_string())
end = dt.end_of(‘month’)
print(end.to_datetime_string())
Output:
2012-09-01 00:00:00
2012-09-30 23:59:59
55以周为单位的两个日期之间的差异
from datetime import date
date1 = date(2020, 12, 23)
date2 = date(2021, 5, 11)
days = abs(date1 - date2).days
print(days // 7)
Output:
19
56将字符串格式的日期转换为 Unix 时间戳
import datetime
stime = ‘15/05/2021’
print(datetime.datetime.strptime(stime, “%d/%m/%Y”).timestamp())
Output:
1621017000.0
57获取最后一个周日和周六的日期
from datetime import datetime, timedelta
def prior_week_end():
return datetime.now() - timedelta(days=((datetime.now().isoweekday() + 1) % 7))
def prior_week_start():
return prior_week_end() - timedelta(days=6)
print(‘Sunday’, format(prior_week_start()))
print(‘Saturday’, format(prior_week_end()))
Output:
Sunday 2021-05-09 13:13:30.057765
Saturday 2021-05-15 13:13:30.058912
58检查对象是否属于 datetime.date 类型
import datetime
x = ‘2012-9-1’
y = datetime.date(2012, 9, 1)
print(isinstance(x, datetime.date))
print(isinstance(y, datetime.date))
Output:
False
True
59获取特定日期的周数
import datetime
print(datetime.date(2020, 5, 15).isocalendar()[1])
Output:
20
60获取 UTC 时间
from datetime import datetime
dt = datetime.utcnow()
print(dt)
Output:
2021-05-15 17:01:31.008808
61获取本周的开始和结束日期
import pendulum
today = pendulum.now()
start = today.start_of(‘week’)
print(start.to_datetime_string())
end = today.end_of(‘week’)
print(end.to_datetime_string())
Output:
2021-05-10 00:00:00
2021-05-16 23:59:59
62两个日期之间的差异(以分钟为单位)
from datetime import datetime
fmt = ‘%Y-%m-%d %H:%M:%S’
d1 = datetime.strptime(‘2010-01-01 17:31:22’, fmt)
d2 = datetime.strptime(‘2010-01-03 17:31:22’, fmt)
days_diff = d2 - d1
print(days_diff.days * 24 * 60)
Output:
2880
63将日期时间对象转换为日期字符串
import datetime
t = datetime.datetime(2020, 12, 23)
x = t.strftime(‘%m/%d/%Y’)
print(x)
Output:
12/23/2020
64获得上周五
from datetime import date
from datetime import timedelta
today = date.today()
offset = (today.weekday() - 4) % 7
friday = today - timedelta(days=offset)
print(friday)
Output:
如果你也是看准了Python,想自学Python,在这里为大家准备了丰厚的免费学习大礼包,带大家一起学习,给大家剖析Python兼职、就业行情前景的这些事儿。
一、Python所有方向的学习路线
Python所有方向路线就是把Python常用的技术点做整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。
二、学习软件
工欲善其必先利其器。学习Python常用的开发软件都在这里了,给大家节省了很多时间。
三、全套PDF电子书
书籍的好处就在于权威和体系健全,刚开始学习的时候你可以只看视频或者听某个人讲课,但等你学完之后,你觉得你掌握了,这时候建议还是得去看一下书籍,看权威技术书籍也是每个程序员必经之路。
四、入门学习视频
我们在看视频学习的时候,不能光动眼动脑不动手,比较科学的学习方法是在理解之后运用它们,这时候练手项目就很适合了。
四、实战案例
光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。
五、面试资料
我们学习Python必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。
成为一个Python程序员专家或许需要花费数年时间,但是打下坚实的基础只要几周就可以,如果你按照我提供的学习路线以及资料有意识地去实践,你就有很大可能成功!
最后祝你好运!!!
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!