日常工作中,用 Python 处理时间格式的数据是非常常见的,今天就来分享 DateTime 相关的示例
文章很长,高低要忍一下,如果忍不了,那就收藏吧,总会用到的
萝卜哥也贴心的做成了PDF,在文末获取!
- 使用 time 模块展示当前日期和时间
- 将天、小时、分钟转换为秒
- 使用 Pandas 获取当前日期和时间
- 将字符串转换为日期时间对象
- 以毫秒为单位获取当前时间
- 以 MST、EST、UTC、GMT 和 HST 获取当前日期时间
- 从给定的日期当中获取星期几
- 计算两个日期时间对象之间的时差
- 将 5 分钟添加到 Unix 时间戳
- 在 Python 中遍历一系列日期
- 巴黎时间更改为纽约时间
- 使用 Python 获得最后7个工作日
- 从今天的日期和一个人的生日推算年龄
- 获得本月的第一个星期二
- 将整数转换为日期对象
- 当前日期减去 N 天的天数
- 比较两个日期
- 从 datetime 对象中提取年份
- 在 Python 中找到星期几
- 从当前日期获取 7 天前的日期
- 将两个日期时间对象之间的差值转换为秒
- 获得任何一个月的第三个星期五
- 从 Python 中的周数获取日期
- 获取特定日期的工作日
- 创建一个 15 分钟前的 DateTime
- 从特定日期获取周的开始和结束日期
- 两个日期之间的差异(以秒为单位)
- 以这种格式获取昨天的日期MMDDYY
- 从今天的日期获取上周三
- 所有可用时区的列表打印
- 获取指定开始日期和结束日期之间的日期范围
- 毫秒转换为数据
- 查找给定日期之后的第一个星期日的日期
- 将(Unix)时间戳秒转换为日期和时间字符串
- 以月为单位的两个日期之间的差异
- 将本地时间字符串转换为 UTC
- 获取当月的最后一个星期四
- 从特定日期查找一年中的第几周
- 从给定日期获取星期几
- 用 AM PM 打印当前时间
- 获得一个月的最后一天
- 从工作日值中获取工作日名称
- 将 N 小时数添加到当前日期时间
- 从当前日期获取年、月、日、小时、分钟
- 获取特定月份和年份的最后一个星期日
- 查找特定日期的年份中的哪一天
- 查找当前日期是工作日还是周末
- 组合 datetime.date 和 datetime.time 对象
- 获得每月的第 5 个星期一
- 将日期时间对象转换为日期对象
- 获取没有微秒的当前日期时间
- 将 N 秒数添加到特定日期时间
- 从当前日期获取两位数的月份和日期
- 从特定日期获取月份数据的开始和结束日期
- 以周为单位的两个日期之间的差异
- 将字符串格式的日期转换为 Unix 时间戳
- 获取最后一个周日和周六的日期
- 检查对象是否属于 datetime.date 类型
- 获取特定日期的周数
- 获取 UTC 时间
- 获取本周的开始和结束日期
- 两个日期之间的差异(以分钟为单位)
- 将日期时间对象转换为日期字符串
- 获得上周五
- 将 3 周添加到任何特定日期
- 在其他两个日期之间生成一个随机日期
- 查找从今天开始的第一个星期一的日期
- 两个日期之间的差异(以天为单位)
- 向当前日期添加六个月
- 将数据时间对象转换为 Unix(时间戳)
- 将年、月、日、时、分、秒的 N 个数字添加到当前日期时间
- 获取指定开始日期和结束日期之间的日期范围
- 减去 N 个年、月、日、时、分、秒到当前日期时间
- 获取指定年份和月份的月份第一天的工作日和月份的天数
- 打印特定年份的所有星期一
- 打印特定年份的日历
- 从月份编号中获取月份名称
- 从给定日期获取一周的开始和结束日期
- 根据当前日期查找上一个和下一个星期一的日期
- 获取当前季度的第一个日期和最后一个日期
1使用 time 模块展示当前日期和时间
import time from time import gmtime, strftime t = time.localtime() print (time.asctime(t)) print(strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())) print(strftime("%A", gmtime())) print(strftime("%D", gmtime())) print(strftime("%B", gmtime())) print(strftime("%y", gmtime())) # Convert seconds into GMT date print(strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime(1234567890)))
Output:
Sun May 7 09:30:37 2017 Sun, 07 May 2017 04:00:37 +0000 Sunday 05/07/17 May 17 Fri, 13 Feb 2009 23:31:30 +0000
2将天、小时、分钟转换为秒
SECONDS_PER_MINUTE = 60 SECONDS_PER_HOUR = 3600 SECONDS_PER_DAY = 86400 #Read the inputs from user days = int(input("Enter number of Days: ")) hours = int(input("Enter number of Hours: ")) minutes = int(input("Enter number of Minutes: ")) seconds = int(input("Enter number of Seconds: ")) #Calculate the days, hours, minutes and seconds total_seconds = days * SECONDS_PER_DAY total_seconds = total_seconds + ( hours * SECONDS_PER_HOUR) total_seconds = total_seconds + ( minutes * SECONDS_PER_MINUTE) total_seconds = total_seconds + seconds #Display the result print("Total number of seconds: ","%d"%(total_seconds))
Output:
Enter number of Days: 5 Enter number of Hours: 36 Enter number of Minutes: 24 Enter number of Seconds: 15 Total number of seconds: 563055
3使用 Pandas 获取当前日期和时间
import pandas as pd print(pd.datetime.now()) print(pd.datetime.now().date()) print(pd.datetime.now().year) print(pd.datetime.now().month) print(pd.datetime.now().day) print(pd.datetime.now().hour) print(pd.datetime.now().minute) print(pd.datetime.now().second) print(pd.datetime.now().microsecond)
Output:
2018-01-19 16:08:28.393553 2018-01-19 2018 1 19 16 8 28 394553
4将字符串转换为日期时间对象
from datetime import datetime from dateutil import parser d1 = "Jan 7 2015 1:15PM" d2 = "2015 Jan 7 1:33PM" # If you know date format date1 = datetime.strptime(d1, '%b %d %Y %I:%M%p') print(type(date1)) print(date1) # If you don't know date format date2 = parser.parse(d2) print(type(date2)) print(date2)
Output:
class 'datetime.datetime' 2015-01-07 13:15:00 class 'datetime.datetime' 2015-01-07 13:33:00
5以毫秒为单位获取当前时间
import time milliseconds = int(round(time.time() * 1000)) print(milliseconds)
Output:
1516364270650
6以 MST、EST、UTC、GMT 和 HST 获取当前日期时间
from datetime import datetime from pytz import timezone mst = timezone('MST') print("Time in MST:", datetime.now(mst)) est = timezone('EST') print("Time in EST:", datetime.now(est)) utc = timezone('UTC') print("Time in UTC:", datetime.now(utc)) gmt = timezone('GMT') print("Time in GMT:", datetime.now(gmt)) hst = timezone('HST') print("Time in HST:", datetime.now(hst))
Output:
Time in MST: 2017-01-19 06:06:14.495605-07:00 Time in EST: 2017-01-19 08:06:14.496606-05:00 Time in UTC: 2017-01-19 13:06:14.496606+00:00 Time in GMT: 2017-01-19 13:06:14.496606+00:00 Time in HST: 2017-01-19 03:06:14.497606-10:00
7从给定的日期当中获取星期几
import datetime dayofweek = datetime.date(2010, 6, 16).strftime("%A") print(dayofweek) # weekday Monday is 0 and Sunday is 6 print("weekday():", datetime.date(2010, 6, 16).weekday()) # isoweekday() Monday is 1 and Sunday is 7 print("isoweekday()", datetime.date(2010, 6, 16).isoweekday()) dayofweek = datetime.datetime.today().strftime("%A") print(dayofweek) print("weekday():", datetime.datetime.today().weekday()) print("isoweekday()", datetime.datetime.today().isoweekday())
Output:
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