15个例子,掌握Python日期时间处理( 二 )

import datetimestart = 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-202022-06-202023-06-202024-06-202025-06-202026-06-202027-06-202028-06-202029-06-202030-06-202001-07-202002-07-202003-07-202004-07-202011巴黎时间更改为纽约时间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:002016-08-07T16:24:30-04:0012使用 Python 获得最后7个工作日【15个例子,掌握Python日期时间处理】from datetime import datefrom 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-182021-05-172021-05-142021-05-132021-05-1213从今天的日期和一个人的生日推算年龄from datetime import datedef 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 - 1else:return today.year - born.yearprint(calculate_age(date(2001, 3, 1)))Output:
2014获得本月的第一个星期二import calendarfrom 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 ifday.weekday() == calendar.TUESDAY and day.month == datetime.today().month][0]print(tues)except IndexError:print('No date found')Output:
2021-05-0415将整数转换为日期对象from datetime import datetimei = 1545730073timestamp = datetime.fromtimestamp(i)print(timestamp)print(type(timestamp))Output:
2018-12-25 14:57:53



推荐阅读