Python中的日期操作总结大全

Python中的日期操作总结大全

游戏|数码彩彩2024-02-24 7:39:09307A+A-

Python里面关于日期计算的自带模块主要就是time和datetime,两个模块提供的侧重功能点不尽相同,本文主要是对我进入工作几年以来所涉及使用到的最频繁最有效的日期计算功能进行的总结和记录,分享给每一个pythoner,希望这些日期计算的小工具能够帮助您提升在工作计算中的效率。

代码实现如下:

#!usr/bin/env python
#encoding:utf-8
 
 
'''
__Author__:沂水寒城
功能: 日期计算操作记录大全
'''
 
import time
import datetime
 
def datetime2String(timestamp,format='%Y-%m-%d %H:%M:%S'):
 '''
 把datetime转成字符串
 '''
 res=timestamp.strftime(format)
 print 'res: ',res
 return res
 
 
def string2Datetime(timestamp,format='%Y-%m-%d %H:%M:%S'):
 '''
 把字符串转成datetime
 '''
 res=datetime.datetime.strptime(timestamp,format)
 print 'res: ',res
 return res
 
 
def string2Timestamp(timestamp):
 '''
 把字符串转成时间戳形式
 '''
 res=time.mktime(string2Datetime(timestamp).timetuple())
 print 'res: ',res
 return res
 
 
def timestamp2String(timestamp,format='%Y-%m-%d %H:%M:%S'):
 '''
 把时间戳转成字符串形式
 '''
 res=time.strftime("%Y-%m-%d-%H", time.localtime(timestamp))
 print 'res: ',res
 return res
 
 
def datetime2Timestamp(one_data):
 '''
 把datetime类型转为时间戳形式
 '''
 res=time.mktime(one_data.timetuple())
 print 'res: ',res
 return res
 
 
def string2Array(timestr='2024-11-11 11:11:11',format='%Y-%m-%d %H:%M:%S'):
 '''
 将字符串转化为时间数组对象
 '''
 timeArray=time.strptime(timestr,format)
 print 'timeArray: ',timeArray 
 print 'year: ',timeArray.tm_year
 print 'month: ',timeArray.tm_mon
 print 'day: ',timeArray.tm_mday
 print 'hour: ',timeArray.tm_hour
 print 'minute: ',timeArray.tm_min
 print 'second: ',timeArray.tm_sec
def calTimeDelta(timestamp1='2024-11-16 19:21:22',timestamp2='2024-12-07 10:21:22',format='%Y-%m-%d %H:%M:%S'):
 '''
 计算给定的两个时间之间的差值
 '''
 T1=datetime.datetime.strptime(timestamp1,format)
 T2=datetime.datetime.strptime(timestamp2,format)
 delta=T2-T1
 day_num=delta.days
 sec_num=delta.seconds
 total_seconds=day_num*86400+sec_num
 print 'dayNum: {0}, secNum: {1}, total_seconds: {2}.'.format(day_num,sec_num,total_seconds)
 return total_seconds
def getBeforeSecond(timestamp,seconds,format='%Y-%m-%d %H:%M:%S'):
 '''
 以给定时间戳为基准,后退 seconds 秒得到对应的时间戳
 '''
 now_time=datetime.datetime.strptime(timestamp,'%Y-%m-%d %H:%M:%S')
 for i in range(seconds):
 now_time-=datetime.timedelta(seconds=1)
 next_timestamp=now_time.strftime('%Y-%m-%d %H:%M:%S')
 print 'next_timestamp: ',next_timestamp
 return next_timestamp 
def getBeforeMinute(timestamp,minutes,format='%Y-%m-%d %H:%M:%S'):
 '''
 以给定时间戳为基准,后退 minutes 分钟得到对应的时间戳
 '''
 now_time=datetime.datetime.strptime(timestamp,'%Y-%m-%d %H:%M:%S')
 for i in range(minutes):
 now_time-=datetime.timedelta(minutes=1)
 next_timestamp=now_time.strftime('%Y-%m-%d %H:%M:%S')
 print 'next_timestamp: ',next_timestamp
 return next_timestamp
 
def getBeforeHour(timestamp,hours,format='%Y-%m-%d %H:%M:%S'):
 '''
 以给定时间戳为基准,后退 hours 个小时得到对应的时间戳
 '''
 now_time=datetime.datetime.strptime(timestamp,'%Y-%m-%d %H:%M:%S')
 for i in range(hours):
 now_time-=datetime.timedelta(hours=1)
 next_timestamp=now_time.strftime('%Y-%m-%d %H:%M:%S')
 print 'next_timestamp: ',next_timestamp
 return next_timestamp
 
def getBeforeDay(timestamp,days,format='%Y-%m-%d %H:%M:%S'):
 '''
 以给定时间戳为基准,后退 days 天得到对应的时间戳
 '''
 now_time=datetime.datetime.strptime(timestamp,'%Y-%m-%d %H:%M:%S')
 for i in range(days):
 now_time-=datetime.timedelta(days=1)
 next_timestamp=now_time.strftime('%Y-%m-%d %H:%M:%S')
 print 'next_timestamp: ',next_timestamp
 return next_timestamp
def getBeforeWeek(timestamp,weeks,format='%Y-%m-%d %H:%M:%S'):
 '''
 以给定时间戳为基准,后退 weeks 个星期后得到对应的时间戳
 '''
 now_time=datetime.datetime.strptime(timestamp,'%Y-%m-%d %H:%M:%S')
 for i in range(weeks):
 now_time-=datetime.timedelta(weeks=1)
 next_timestamp=now_time.strftime('%Y-%m-%d %H:%M:%S')
 print 'next_timestamp: ',next_timestamp
 return next_timestamp
def getBeforeMonth(timestamp,months,format='%Y-%m-%d %H:%M:%S'):
 '''
 以给定时间戳为基准,后退 months 个月后得到对应的时间戳
 '''
 from calendar import monthrange
 now_time=datetime.datetime.strptime(timestamp,'%Y-%m-%d %H:%M:%S')
 year,month,day=[int(one) for one in str(now_time).split(' ')[0].split('-')]
 for i in range(months):
 now_time-=datetime.timedelta(days=monthrange(year,month)[1])
 next_timestamp=now_time.strftime('%Y-%m-%d %H:%M:%S')
 print 'next_timestamp: ',next_timestamp
 return next_timestamp
def getBeforeYear(timestamp,years,format='%Y-%m-%d %H:%M:%S'):
 '''
 以给定时间戳为基准,后退 years 年后得到对应的时间戳
 '''
 from calendar import monthrange
 now_time=datetime.datetime.strptime(timestamp,'%Y-%m-%d %H:%M:%S')
 year,month,day=[int(one) for one in str(now_time).split(' ')[0].split('-')]
 for j in range(years):
 for i in range(12):
 now_time-=datetime.timedelta(days=monthrange(year,month)[1])
 next_timestamp=now_time.strftime('%Y-%m-%d %H:%M:%S')
 print 'next_timestamp: ',next_timestamp
 return next_timestamp
def getFutureSecond(timestamp,seconds,format='%Y-%m-%d %H:%M:%S'):
 '''
 以给定时间戳为基准,前进 seconds 秒得到对应的时间戳
 '''
 now_time=datetime.datetime.strptime(timestamp,'%Y-%m-%d %H:%M:%S')
 for i in range(seconds):
 now_time+=datetime.timedelta(seconds=1)
 next_timestamp=now_time.strftime('%Y-%m-%d %H:%M:%S')
 print 'next_timestamp: ',next_timestamp
 return next_timestamp
def getFutureMinute(timestamp,minutes,format='%Y-%m-%d %H:%M:%S'):
 '''
 以给定时间戳为基准,前进 minutes 分钟得到对应的时间戳
 '''
 now_time=datetime.datetime.strptime(timestamp,'%Y-%m-%d %H:%M:%S')
 for i in range(minutes):
 now_time+=datetime.timedelta(minutes=1)
 next_timestamp=now_time.strftime('%Y-%m-%d %H:%M:%S')
 print 'next_timestamp: ',next_timestamp
 return next_timestamp
 
def getFutureHour(timestamp,hours,format='%Y-%m-%d %H:%M:%S'):
 '''
 以给定时间戳为基准,前进 hours 个小时得到对应的时间戳
 '''
 now_time=datetime.datetime.strptime(timestamp,'%Y-%m-%d %H:%M:%S')
 for i in range(hours):
 now_time+=datetime.timedelta(hours=1)
 next_timestamp=now_time.strftime('%Y-%m-%d %H:%M:%S')
 print 'next_timestamp: ',next_timestamp
 return next_timestamp
def getFutureDay(timestamp,days,format='%Y-%m-%d %H:%M:%S'):
 '''
 以给定时间戳为基准,前进 days 天得到对应的时间戳
 '''
 now_time=datetime.datetime.strptime(timestamp,'%Y-%m-%d %H:%M:%S')
 for i in range(days):
 now_time+=datetime.timedelta(days=1)
 next_timestamp=now_time.strftime('%Y-%m-%d %H:%M:%S')
 print 'next_timestamp: ',next_timestamp
 return next_timestamp
def getFutureWeek(timestamp,weeks,format='%Y-%m-%d %H:%M:%S'):
 '''
 以给定时间戳为基准,前进 weeks 个星期后得到对应的时间戳
 '''
 now_time=datetime.datetime.strptime(timestamp,'%Y-%m-%d %H:%M:%S')
 for i in range(weeks):
 now_time+=datetime.timedelta(weeks=1)
 next_timestamp=now_time.strftime('%Y-%m-%d %H:%M:%S')
 print 'next_timestamp: ',next_timestamp
 return next_timestamp
def getFutureMonth(timestamp,months,format='%Y-%m-%d %H:%M:%S'):
 '''
 以给定时间戳为基准,前进 months 个月后得到对应的时间戳
 '''
 from calendar import monthrange
 now_time=datetime.datetime.strptime(timestamp,'%Y-%m-%d %H:%M:%S')
 year,month,day=[int(one) for one in str(now_time).split(' ')[0].split('-')]
 for i in range(months):
 now_time+=datetime.timedelta(days=monthrange(year,month)[1])
 next_timestamp=now_time.strftime('%Y-%m-%d %H:%M:%S')
 print 'next_timestamp: ',next_timestamp
 return next_timestamp
def getFutureYear(timestamp,years,format='%Y-%m-%d %H:%M:%S'):
 '''
 以给定时间戳为基准,前进 years 年后得到对应的时间戳
 '''
 from calendar import monthrange
 now_time=datetime.datetime.strptime(timestamp,'%Y-%m-%d %H:%M:%S')
 year,month,day=[int(one) for one in str(now_time).split(' ')[0].split('-')]
 for j in range(years):
 for i in range(12):
 now_time+=datetime.timedelta(days=monthrange(year,month)[1])
 next_timestamp=now_time.strftime('%Y-%m-%d %H:%M:%S')
 print 'next_timestamp: ',next_timestamp
 return next_timestamp
def getNowTimeStamp(format='%Y%m%d'):
 '''
 获取当前的时间戳
 '''
 now_time=str(datetime.datetime.now().strftime(format))
 nowTime=str(time.strftime(format,time.localtime(time.time())))
 print 'now_time:',now_time
 print 'nowTime:',nowTime
def calDayWeek(one_date):
 '''
 计算指定日期是第几周
 '''
 year1,month1,day1=[int(one) for one in one_date.split('/')]
 tmp=datetime.date(year1,month1,day1)
 info=list(tmp.isocalendar()) 
 print '{0}是第{1}周周{2}'.format(one_date,info[1],info[-1])
 
 
def calDayAfterWeeksDate(one_date,n_weeks=100):
 '''
 计算指定日期后n_weeks周后是某年某月某日
 '''
 year1,month1,day1=[int(one) for one in one_date.split('/')]
 tmp=datetime.date(year1,month1,day1)
 delta=datetime.timedelta(weeks=n_weeks)
 new_date=(tmp+delta).strftime("%Y-%m-%d %H:%M:%S").split(' ')[0]
 print '{0}过{1}周后日期为:{2}'.format(one_date,n_weeks,new_date)
 
 
def calDayAfterDaysDate(one_date,n_days=100):
 '''
 计算指定日期后n_days天后是某年某月某日
 '''
 year1,month1,day1=[int(one) for one in one_date.split('/')]
 tmp=datetime.date(year1,month1,day1)
 delta=datetime.timedelta(days=n_days)
 new_date=(tmp+delta).strftime("%Y-%m-%d %H:%M:%S").split(' ')[0]
 print '{0}过{1}天后日期为:{2}'.format(one_date,n_days,new_date)
 
if __name__=='__main__':
 #与周相关的计算
 calDayWeek('2015/09/21')
 calDayAfterWeeksDate('2015/09/21',n_weeks=100)
 calDayAfterDaysDate('2015/09/21',n_days=100)
 #计算时间间隔秒数
 calTimeDelta(timestamp1='2024-11-16 19:21:22',timestamp2='2024-12-07 10:21:22',format='%Y-%m-%d %H:%M:%S')
 
 #生成当前时刻的时间戳
 format_list=['%Y%m%d','%Y:%m:%d','%Y-%m-%d','%Y%m%d%H%M%S','%Y-%m-%d %H:%M:%S','%Y/%m/%d/%H:%M:%S']
 for format in format_list:
 getNowTimeStamp(format=format)
 #生成过去间隔指定长度时刻的时间戳
 getBeforeSecond('2024-12-19 11:00:00',40,format='%Y-%m-%d %H:%M:%S')
 getBeforeMinute('2024-12-19 11:00:00',10,format='%Y-%m-%d %H:%M:%S')
 getBeforeHour('2024-12-19 11:00:00',8,format='%Y-%m-%d %H:%M:%S')
 getBeforeDay('2024-12-19 11:00:00',5,format='%Y-%m-%d %H:%M:%S')
 getBeforeWeek('2024-12-19 11:00:00',2,format='%Y-%m-%d %H:%M:%S')
 getBeforeMonth('2024-12-19 11:00:00',3,format='%Y-%m-%d %H:%M:%S')
 getBeforeYear('2024-12-19 11:00:00',10,format='%Y-%m-%d %H:%M:%S')
 #生成未来间隔指定长度时刻的时间戳
 getFutureSecond('2024-12-19 11:00:00',40,format='%Y-%m-%d %H:%M:%S')
 getFutureMinute('2024-12-19 11:00:00',10,format='%Y-%m-%d %H:%M:%S')
 getFutureHour('2024-12-19 11:00:00',8,format='%Y-%m-%d %H:%M:%S')
 getFutureDay('2024-12-19 11:00:00',5,format='%Y-%m-%d %H:%M:%S')
 getFutureWeek('2024-12-19 11:00:00',2,format='%Y-%m-%d %H:%M:%S')
 getFutureMonth('2024-12-19 11:00:00',3,format='%Y-%m-%d %H:%M:%S')
 getFutureYear('2024-12-19 11:00:00',10,format='%Y-%m-%d %H:%M:%S')

简单对上述代码测试,输出结果如下:

2015/09/21是第39周周1
2015/09/21过100周后日期为:2024-08-21
2015/09/21过100天后日期为:2015-12-30
dayNum: 20, secNum: 54000, total_seconds: 1782000.
now_time: 20240801
nowTime: 20240801
now_time: 2024:08:01
nowTime: 2024:08:01
now_time: 2024-08-01
nowTime: 2024-08-01
now_time: 20240801151336
nowTime: 20240801151336
now_time: 2024-08-01 15:13:36
nowTime: 2024-08-01 15:13:36
now_time: 2024/08/01/15:13:36
nowTime: 2024/08/01/15:13:36
next_timestamp: 2024-12-19 10:59:20
next_timestamp: 2024-12-19 10:50:00
next_timestamp: 2024-12-19 03:00:00
next_timestamp: 2024-12-14 11:00:00
next_timestamp: 2024-12-05 11:00:00
next_timestamp: 2024-09-17 11:00:00
next_timestamp: 2008-10-12 11:00:00
next_timestamp: 2024-12-19 11:00:40
next_timestamp: 2024-12-19 11:10:00
next_timestamp: 2024-12-19 19:00:00
next_timestamp: 2024-12-24 11:00:00
next_timestamp: 2024-01-02 11:00:00
next_timestamp: 2024-03-22 11:00:00
next_timestamp: 2029-02-24 11:00:00

个人的经验累积,需要的可以拿去使用哈,欢迎交流学习!

点击这里复制本文地址 版权声明:本文内容由网友提供,该文观点仅代表作者本人。本站(https://www.angyang.net.cn)仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件举报,一经查实,本站将立刻删除。

昂扬百科 © All Rights Reserved.  渝ICP备2023000803号-3网赚杂谈