百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 热门文章 > 正文

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

bigegpt 2024-09-10 11:24 4 浏览

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='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_sec
def 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_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='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周周1
2015/09/21过100周后日期为:2017-08-21
2015/09/21过100天后日期为:2015-12-30
dayNum: 20, secNum: 54000, total_seconds: 1782000.
now_time: 20190801
nowTime: 20190801
now_time: 2019:08:01
nowTime: 2019:08:01
now_time: 2019-08-01
nowTime: 2019-08-01
now_time: 20190801151336
nowTime: 20190801151336
now_time: 2019-08-01 15:13:36
nowTime: 2019-08-01 15:13:36
now_time: 2019/08/01/15:13:36
nowTime: 2019/08/01/15:13:36
next_timestamp: 2018-12-19 10:59:20
next_timestamp: 2018-12-19 10:50:00
next_timestamp: 2018-12-19 03:00:00
next_timestamp: 2018-12-14 11:00:00
next_timestamp: 2018-12-05 11:00:00
next_timestamp: 2018-09-17 11:00:00
next_timestamp: 2008-10-12 11:00:00
next_timestamp: 2018-12-19 11:00:40
next_timestamp: 2018-12-19 11:10:00
next_timestamp: 2018-12-19 19:00:00
next_timestamp: 2018-12-24 11:00:00
next_timestamp: 2019-01-02 11:00:00
next_timestamp: 2019-03-22 11:00:00
next_timestamp: 2029-02-24 11:00:00

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

相关推荐

Go语言泛型-泛型约束与实践(go1.7泛型)

来源:械说在Go语言中,Go泛型-泛型约束与实践部分主要探讨如何定义和使用泛型约束(Constraints),以及如何在实际开发中利用泛型进行更灵活的编程。以下是详细内容:一、什么是泛型约束?**泛型...

golang总结(golang实战教程)

基础部分Go语言有哪些优势?1简单易学:语法简洁,减少了代码的冗余。高效并发:内置强大的goroutine和channel,使并发编程更加高效且易于管理。内存管理:拥有自动垃圾回收机制,减少内...

Go 官宣:新版 Protobuf API(go pro版本)

原文作者:JoeTsai,DamienNeil和HerbieOng原文链接:https://blog.golang.org/a-new-go-api-for-protocol-buffer...

Golang开发的一些注意事项(一)(golang入门项目)

1.channel关闭后读的问题当channel关闭之后再去读取它,虽然不会引发panic,但会直接得到零值,而且ok的值为false。packagemainimport"...

golang 托盘菜单应用及打开系统默认浏览器

之前看到一个应用,用go语言编写,说是某某程序的windows图形化客户端,体验一下发现只是一个托盘,然后托盘菜单的控制面板功能直接打开本地浏览器访问程序启动的webserver网页完成gui相关功...

golang标准库每日一库之 io/ioutil

一、核心函数概览函数作用描述替代方案(Go1.16+)ioutil.ReadFile(filename)一次性读取整个文件内容(返回[]byte)os.ReadFileioutil.WriteFi...

文件类型更改器——GoLang 中的 CLI 工具

我是如何为一项琐碎的工作任务创建一个简单的工具的,你也可以上周我开始玩GoLang,它是一种由Google制作的类C编译语言,非常轻量和快速,事实上它经常在Techempower的基准测...

Go (Golang) 中的 Channels 简介(golang channel长度和容量)

这篇文章重点介绍Channels(通道)在Go中的工作方式,以及如何在代码中使用它们。在Go中,Channels是一种编程结构,它允许我们在代码的不同部分之间移动数据,通常来自不同的goro...

Golang引入泛型:Go将Interface「」替换为“Any”

现在Go将拥有泛型:Go将Interface{}替换为“Any”,这是一个类型别名:typeany=interface{}这会引入了泛型作好准备,实际上,带有泛型的Go1.18Beta...

一文带你看懂Golang最新特性(golang2.0特性)

作者:腾讯PCG代码委员会经过十余年的迭代,Go语言逐渐成为云计算时代主流的编程语言。下到云计算基础设施,上到微服务,越来越多的流行产品使用Go语言编写。可见其影响力已经非常强大。一、Go语言发展历史...

Go 每日一库之 java 转 go 遇到 Apollo?让 agollo 来平滑迁移

以下文章来源于GoOfficialBlog,作者GoOfficialBlogIntroductionagollo是Apollo的Golang客户端Apollo(阿波罗)是携程框架部门研...

Golang使用grpc详解(golang gcc)

gRPC是Google开源的一种高性能、跨语言的远程过程调用(RPC)框架,它使用ProtocolBuffers作为序列化工具,支持多种编程语言,如C++,Java,Python,Go等。gR...

Etcd服务注册与发现封装实现--golang

服务注册register.gopackageregisterimport("fmt""time"etcd3"github.com/cor...

Golang:将日志以Json格式输出到Kafka

在上一篇文章中我实现了一个支持Debug、Info、Error等多个级别的日志库,并将日志写到了磁盘文件中,代码比较简单,适合练手。有兴趣的可以通过这个链接前往:https://github.com/...

如何从 PHP 过渡到 Golang?(php转golang)

我是PHP开发者,转Go两个月了吧,记录一下使用Golang怎么一步步开发新项目。本着有坑填坑,有错改错的宗旨,从零开始,开始学习。因为我司没有专门的Golang大牛,所以我也只能一步步自己去...