翼度科技»论坛 编程开发 python 查看内容

Python处理日期方法大全、三十种方法

4

主题

4

帖子

12

积分

新手上路

Rank: 1

积分
12
一、使用 time 模块展示当前日期和时间
  1. import time
  2. from time import gmtime, strftime
  3. t = time.localtime()  
  4. print (time.asctime(t))  # Sun May 7 09:30:37 2017
  5. print(strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()))  # Sun, 07 May 2017 04:00:37 +0000
  6. print(strftime("%A", gmtime()))  # Sunday
  7. print(strftime("%D", gmtime()))  # 05/07/17
  8. print(strftime("%B", gmtime()))  # May
  9. print(strftime("%y", gmtime()))  # 17
  10. # Convert seconds into GMT date
  11. print(strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime(1234567890)))  # Fri, 13 Feb 2009 23:31:30 +0000
复制代码
二、将天、小时、分钟转换为秒
  1. SECONDS_PER_MINUTE = 60
  2. SECONDS_PER_HOUR = 3600
  3. SECONDS_PER_DAY = 86400
  4. # 输入天、小时、分钟、秒的数量
  5. days = int(input("Enter number of Days: "))
  6. hours = int(input("Enter number of Hours: "))
  7. minutes = int(input("Enter number of Minutes: "))
  8. seconds = int(input("Enter number of Seconds: "))
  9. # 计算
  10. total_seconds = days * SECONDS_PER_DAY
  11. total_seconds = total_seconds + ( hours * SECONDS_PER_HOUR)
  12. total_seconds = total_seconds + ( minutes * SECONDS_PER_MINUTE)
  13. total_seconds = total_seconds + seconds
  14. # 结果
  15. print("Total number of seconds: ","%d"%(total_seconds))
  16. '''
  17. Enter number of Days: 5
  18. Enter number of Hours: 36
  19. Enter number of Minutes: 24
  20. Enter number of Seconds: 15
  21. Total number of seconds: 563055
  22. '''
复制代码
三、使用 Pandas 获取当前日期和时间
  1. import pandas as pd
  2. print(pd.datetime.now())  # 2018-01-19 16:08:28.393553
  3. print(pd.datetime.now().date())  # 2018-01-19
  4. print(pd.datetime.now().year)  # 2018
  5. print(pd.datetime.now().month)  # 1
  6. print(pd.datetime.now().day)  # 19
  7. print(pd.datetime.now().hour)  # 16
  8. print(pd.datetime.now().minute)  # 8
  9. print(pd.datetime.now().second)  # 28
  10. print(pd.datetime.now().microsecond)  # 394553
复制代码
四、将字符串转换为日期时间对象
  1. from datetime import datetime
  2. from dateutil import parser
  3. d1 = "Jan 7 2015  1:15PM"
  4. d2 = "2015 Jan 7  1:33PM"
  5. # If you know date format
  6. date1 = datetime.strptime(d1, '%b %d %Y %I:%M%p')
  7. print(type(date1))  # class 'datetime.datetime'
  8. print(date1)  # 2015-01-07 13:15:00
  9. # If you don't know date format
  10. date2 = parser.parse(d2)
  11. print(type(date2))  # class 'datetime.datetime'
  12. print(date2)  # 2015-01-07 13:33:00
复制代码
五、以毫秒为单位获取当前时间
  1. import time
  2. milliseconds = int(round(time.time() * 1000))
  3. print(milliseconds)  # 1516364270650
复制代码
六、以 MST、EST、UTC、GMT 和 HST 获取当前日期时间
  1. from datetime import datetime
  2. from pytz import timezone
  3. mst = timezone('MST')
  4. print("Time in MST:", datetime.now(mst))  # Time in MST: 2017-01-19 06:06:14.495605-07:00
  5. est = timezone('EST')
  6. print("Time in EST:", datetime.now(est))  # Time in EST: 2017-01-19 08:06:14.496606-05:00
  7. utc = timezone('UTC')
  8. print("Time in UTC:", datetime.now(utc))  # Time in UTC: 2017-01-19 13:06:14.496606+00:00
  9. gmt = timezone('GMT')
  10. print("Time in GMT:", datetime.now(gmt))  # Time in GMT: 2017-01-19 13:06:14.496606+00:00
  11. hst = timezone('HST')
  12. print("Time in HST:", datetime.now(hst))  # Time in HST: 2017-01-19 03:06:14.497606-10:00
复制代码
七、从给定的日期当中获取星期几
  1. import datetime
  2. dayofweek = datetime.date(2010, 6, 16).strftime("%A")
  3. print(dayofweek)  # Wednesday
  4. # weekday()方法: 0代表周一,6代表周日
  5. print("weekday():", datetime.date(2010, 6, 16).weekday())  # weekday(): 2
  6. # isoweekday() 方法: 1代表周一,7代表周日
  7. print("isoweekday()", datetime.date(2010, 6, 16).isoweekday())  # isoweekday() 3
  8. dayofweek = datetime.datetime.today().strftime("%A")
  9. print(dayofweek)  # Friday
  10. print("weekday():", datetime.datetime.today().weekday())  # weekday(): 4
  11. print("isoweekday()", datetime.datetime.today().isoweekday())  # isoweekday(): 5
复制代码
八、计算两个日期时间对象之间的时差
  1. import datetime
  2. from datetime import timedelta
  3. datetimeFormat = '%Y-%m-%d %H:%M:%S.%f'
  4. date1 = '2016-04-16 10:01:28.585'
  5. date2 = '2016-03-10 09:56:28.067'
  6. diff = datetime.datetime.strptime(date1, datetimeFormat)\
  7.     - datetime.datetime.strptime(date2, datetimeFormat)
  8. print("Difference:", diff)  # Difference: 37 days, 0:05:00.518000
  9. print("Days:", diff.days)  # Days: 37
  10. print("Microseconds:", diff.microseconds)  # Microseconds: 518000
  11. print("Seconds:", diff.seconds)  # Seconds: 300
复制代码
九、将 5 分钟添加到 Unix 时间戳
  1. import datetime
  2. import calendar
  3. future = datetime.datetime.utcnow() + datetime.timedelta(minutes=5)
  4. print(calendar.timegm(future.timetuple()))  # 1621069619
复制代码
十、遍历一系列日期
  1. import datetime
  2. start = datetime.datetime.strptime("21-06-2020", "%d-%m-%Y")
  3. end = datetime.datetime.strptime("05-07-2020", "%d-%m-%Y")
  4. date_generated = [start + datetime.timedelta(days=x) for x in range(0, (end - start).days)]
  5. for date in date_generated:
  6.     print(date.strftime("%d-%m-%Y"))
复制代码
十一、巴黎时间更改为纽约时间
  1. import pendulum
  2. in_paris = pendulum.datetime(2016, 8, 7, 22, 24, 30, tz='Europe/Paris')
  3. print(in_paris)  # 2016-08-07T22:24:30+02:00
  4. in_us = in_paris.in_timezone('America/New_York')
  5. print(in_us)  # 2016-08-07T16:24:30-04:00
复制代码
十二、使用 Python 获得最后7个工作日
  1. from datetime import date
  2. from datetime import timedelta
  3. today = date.today()
  4. for i in range(7):
  5.     d = today - timedelta(days=i)
  6.     if d.weekday() < 5:
  7.         print(d)
复制代码
十三、从今天的日期和一个人的生日推算年龄
  1. from datetime import date
  2. def calculate_age(born):
  3.     today = date.today()
  4.     try:
  5.         birthday = born.replace(year=today.year)
  6.     except ValueError:
  7.         birthday = born.replace(year=today.year, month=born.month + 1, day=1)
  8.     if birthday > today:
  9.         return today.year - born.year - 1
  10.     else:
  11.         return today.year - born.year
  12. print(calculate_age(date(2001, 3, 1)))
复制代码
十四、获得本月的第一个星期二
  1. import calendar
  2. from datetime import datetime
  3. c = calendar.Calendar(firstweekday=calendar.SUNDAY)
  4. monthcal = c.monthdatescalendar(datetime.today().year, datetime.today().month)
  5. #Python小白学习交流群:153708845  
  6. try:
  7.     tues = [day for week in monthcal for day in week if
  8.             day.weekday() == calendar.TUESDAY and day.month == datetime.today().month][0]
  9.     print(tues)
  10. except IndexError:
  11.     print('No date found')
复制代码
十五、将整数转换为日期对象
  1. from datetime import datetime
  2. i = 1545730073
  3. timestamp = datetime.fromtimestamp(i)
  4. print(timestamp)  # 2018-12-25 14:57:53
  5. print(type(timestamp))
复制代码
十六、当前日期减去 N 天的天数
  1. from datetime import datetime, timedelta
  2. d = datetime.today() - timedelta(days=5)
  3. print(d)
复制代码
十七、比较两个日期
  1. import datetime
  2. a = datetime.datetime(2020, 12, 31, 23, 59, 59)
  3. b = datetime.datetime(2020, 11, 30, 23, 59, 59)
  4. print(a < b)
  5. print(a > b)
复制代码
十八、从 datetime 对象中提取年份
  1. import datetime
  2. year = datetime.date.today().year
  3. print(year)
复制代码
十九、根据日期找到星期几
  1. import pendulum
  2. dt = pendulum.parse('2021-05-18')
  3. print(dt.day_of_week)  # 2
  4. dt = pendulum.parse('2021-05-01')
  5. print(dt.day_of_week) # 6
  6. dt = pendulum.parse('2021-05-21')
  7. print(dt.day_of_week) # 5
复制代码
二十、从当前日期获取 7 天前的日期
  1. from datetime import datetime, timedelta
  2. now = datetime.now()
  3. for x in range(7):
  4.     d = now - timedelta(days=x)
  5.     print(d.strftime("%Y-%m-%d"))
复制代码
二十一、将两个日期时间对象之间的差值转换为秒
  1. import datetime
  2. time1 = datetime.datetime.strptime('19 01 2021', '%d %m %Y')
  3. time2 = datetime.datetime.strptime('25 01 2021', '%d %m %Y')
  4. difference = time2 - time1
  5. print(difference)  # 6 days, 0:00:00
  6. seconds = difference.total_seconds()
  7. print(seconds)  # 518400.0
复制代码
二十二、获得任何一个月的第N个星期五
  1. import calendar
  2. # 取2021年5月的第三个星期五
  3. c = calendar.Calendar(firstweekday=calendar.SUNDAY)
  4. year = 2021
  5. month = 5
  6. n = 2  # 取第三个
  7. monthcal = c.monthdatescalendar(year, month)
  8. try:
  9.     third_friday = [
  10.         day for week in monthcal
  11.             for day in week if
  12.                 day.weekday() == calendar.FRIDAY and day.month == month
  13.     ][n]
  14.     print(third_friday)  # 2021-05-21
  15. except IndexError:
  16.     print('No date found')
复制代码
二十三、根据周数获取日期
  1. import datetime
  2. from dateutil.relativedelta import relativedelta
  3. week = 25
  4. year = 2021
  5. date = datetime.date(year, 1, 1) + relativedelta(weeks=+week)
  6. print(date)  # 2021-06-25
复制代码
二十四、获取特定日期的工作日
  1. import datetime
  2. print(datetime.date(2020, 5, 15).isocalendar()[2])  # 5
复制代码
二十五、创建一个 15 分钟前的 DateTime
  1. import datetime
  2. #Python小白学习交流群:153708845  
  3. dt = datetime.datetime.now() - datetime.timedelta(minutes=15)
  4. print(dt)  # 2021-05-15 22:25:55.897365
复制代码
二十六、从特定日期获取周的开始和结束日期
  1. import pendulum
  2. dt = pendulum.datetime(2012, 9, 5)
  3. start = dt.start_of('week')
  4. print(start.to_datetime_string())  # 2012-09-03 00:00:00
  5. end = dt.end_of('week')
  6. print(end.to_datetime_string())  # 2012-09-09 23:59:59
复制代码
二十七、两个日期之间的差异(以秒为单位)
  1. from datetime import datetime
  2. #Python小白学习交流群:153708845
  3. fmt = '%Y-%m-%d %H:%M:%S'
  4. d1 = datetime.strptime('2020-01-01 17:31:22', fmt)
  5. d2 = datetime.strptime('2020-01-03 17:31:22', fmt)
  6. days_diff = d2 - d1
  7. print(days_diff.days * 24 * 60 * 60)  # 172800
复制代码
二十八、以这种格式获取昨天的日期MMDDYY
  1. from datetime import date, timedelta
  2. yesterday = date.today() - timedelta(days=1)
  3. print(yesterday.strftime('%m%d%y'))  # 051421
复制代码
二十九、根据今天的日期获取上周三的日期
  1. from datetime import date
  2. from datetime import timedelta
  3. today = date.today()
  4. offset = (today.weekday() - 2) % 7
  5. wednesday = today - timedelta(days=offset)
  6. print(wednesday)  # 2021-05-12
复制代码
三十、所有可用时区的列表打印
  1. import pytz
  2. for i in pytz.all_timezones:
  3.     print(i)
复制代码
来源:https://www.cnblogs.com/xxpythonxx/p/17817779.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具