龙空技术网

Python中的日期操作总结大全「值得收藏」

yishuihancheng 492

前言:

此时各位老铁们对“python当前时间戳”大约比较注意,兄弟们都想要剖析一些“python当前时间戳”的相关资讯。那么小编也在网络上收集了一些关于“python当前时间戳””的相关资讯,希望看官们能喜欢,兄弟们快快来了解一下吧!

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

代码实现如下:

#!usr/bin/env python#encoding:utf-8  '''__Author__:沂水寒城功能: 日期计算操作记录大全''' import timeimport 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='2018-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_secdef calTimeDelta(timestamp1='2018-11-16 19:21:22',timestamp2='2018-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_secondsdef 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_timestampdef 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_timestampdef 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_timestampdef 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_timestampdef 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_timestampdef 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_timestampdef 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_timestampdef 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_timestampdef 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_timestampdef 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_timestampdef 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:',nowTimedef 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='2018-11-16 19:21:22',timestamp2='2018-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('2018-12-19 11:00:00',40,format='%Y-%m-%d %H:%M:%S') getBeforeMinute('2018-12-19 11:00:00',10,format='%Y-%m-%d %H:%M:%S') getBeforeHour('2018-12-19 11:00:00',8,format='%Y-%m-%d %H:%M:%S') getBeforeDay('2018-12-19 11:00:00',5,format='%Y-%m-%d %H:%M:%S') getBeforeWeek('2018-12-19 11:00:00',2,format='%Y-%m-%d %H:%M:%S') getBeforeMonth('2018-12-19 11:00:00',3,format='%Y-%m-%d %H:%M:%S') getBeforeYear('2018-12-19 11:00:00',10,format='%Y-%m-%d %H:%M:%S') #生成未来间隔指定长度时刻的时间戳 getFutureSecond('2018-12-19 11:00:00',40,format='%Y-%m-%d %H:%M:%S') getFutureMinute('2018-12-19 11:00:00',10,format='%Y-%m-%d %H:%M:%S') getFutureHour('2018-12-19 11:00:00',8,format='%Y-%m-%d %H:%M:%S') getFutureDay('2018-12-19 11:00:00',5,format='%Y-%m-%d %H:%M:%S') getFutureWeek('2018-12-19 11:00:00',2,format='%Y-%m-%d %H:%M:%S') getFutureMonth('2018-12-19 11:00:00',3,format='%Y-%m-%d %H:%M:%S') getFutureYear('2018-12-19 11:00:00',10,format='%Y-%m-%d %H:%M:%S')

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

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

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

标签: #python当前时间戳 #python中tmp #python时间转换成时间戳 #python获取当前分钟 #python输出某年某月的日历