当前位置: 首页 > 后端技术 > Python

Python时间模块常用操作总结

时间:2023-03-26 19:21:02 Python

时间模块常用操作总结为以下函数:#!/usr/bin/envpython#-*-coding:utf-8-*-importsysreload(sys)sys.setdefaultencoding('utf-8')importtimeimportdatetimeimportcalendardefsecond_to_datetime_string(seconds):"""将秒从AD0转换为日期时间字符串格式:paramseconds:thesecondsfromAD0:return:datetimestringForm"""s=time.strftime('%Y-%m-%d%H:%M:%S',time.localtime(float(seconds)))year=s.split('-',1)[0]rest=s.split('-',1)[1]year=int(year)-1970#datetime从1970年开始,所以计算时需要减去1970return'{}-{}'.format(str(year),rest)defgregorian_date_to_str(year,month,day):"""将AD日期转换成字符串,年占4位,月占2位,日占2位,如果位数不足,makeup0:paramyear:年,如2017:parammonth:月,如8或08:paramday:日,比如12or02or2:return:返回固定数字的字符串,比如2017-08-22"""return'{}-{}-{}'.format(year,monthiflen(str(month))==2else'0{}'.format(month),dayiflen(str(day))==2else'0{}'。格式(天))def公历_date_to_str_1(year,month,day):"""将AD日期转换成字符串,年占4位,月占2位,日占2位,位数不足则补0:paramyear:year,如2017:parammonth:月份,如8或08:paramday:日,如12或02或2:return:返回固定数字的字符串,不带-,如20170822"""return'{{}{}'。格式(年,月如果len(str(month))==2else'0{}'.format(month),dayiflen(str(day))==2else'0{}'.format(day))defget_element_from_date_str(date_str):"""获取日期字符串的年月日"""returndate_str[0:4],date_str[4:6],date_str[6:8]defis_valid_date(date_str):"""判断是否为有效日期字符串"""try:time.strptime(date_str,'%Y%m%d')returnTrueexceptValueError:returnFalsedefget_latter_1_day_str(date_str):"""之后gettingdata_str一天的日期字符串:paramdate_str:指定日期字符串:return:返回指定日期字符串后一天的日期字符串"""dt=datetime.datetime.strptime(date_str,'%Y%m%d')one_day=datetime.timedelta(days=1)former_day=dt+one_dayreturnformer_day.strftime('%Y%m%d')defget_latter_n_day_str(date_str,n):"""获取日期字符串后n天data_str:paramdate_str:指定日期字符串:return:返回指定日期字符串后n天的日期字符串"""dt=datetime.datetime.strptime(date_str,'%Y%m%d')one_day=datetime.timedelta(days=days)former_day=dt+one_dayreturnformer_day.strftime('%Y%m%d')defget_yesterday_str():"""获取昨天的日期字符串:return:返回昨天的日期字符串"""today=datetime.date.today()one_day=datetime.timedelta(days=1)yesterday=today-one_dayreturnyesterday.strftime('%Y%m%d')defget_former_1_day_str(date_str):"""获取data_str前一天的日期字符串:paramdate_str:指定日期字符串:return:返回指定日期字符串前一天的日期字符串"""dt=datetime.datetime.strptime(date_str,'%Y%m%d')one_day=datetime.timedelta(days=1)former_day=dt-one_day返回former_day.strftime('%Y%m%d')defget_former_n_day_str(date_str,n):"""获取日期字符串ngofndaysbeforedata_str:paramdate_str:指定日期字符串:paramn:numberofday:return:返回指定日期字符串前n天的日期字符串"""dt=datetime.datetime.strptime(date_str,'%Y%m%d')n_day=datetime.timedelta(days=n)former_n_day=dt-n_day返回former_n_day.strftime('%Y%m%d')defget_universal_time():"""获取当前时间:return:返回当前时间,格式:2017-08-2902:43:19"""t=time.gmtime()time_tuple=(t.tm_year,t.tm_mon,t.tm_mday,t.tm_hour,t.tm_min,t.tm_sec)dt=datetime.datetime(*time_tuple)返回dt.strftime('%Y-%m-%d%H:%M:%S')defdatetime_to_gregorian_seconds(dt):"""获取从公元0月1日到当天0:00经过的秒数:paramdt:datetime.datetimetype:return:从公元0月1日返回到当天0:00过去的秒数"""d=dt.date()t=dt.time()#toordinal从1年1月1日开始,erlang的datetime_to_gregorian_seconds和date_to_gregorian_days从0年1月1日开始#天数不算,所以需要减去1天return(d.toordinal()+365-1)*86400+time_to_second(t.hour,t.minute,t.second)deftime_to_second(time_h,time_m,time_s):"""根据给定的time_h,time_m,time_s计算当天经过的时间,单位是秒:paramtime_h:hour:paramtime_m:minute:paramtime_s:second:return:返回计算出的秒"""returnint(time_h)*3600+int(time_m)*60+int(time_s)defutc_time_to_second(utc_time):"""根据to给定的utc_time计算一天中经过的时间,以秒为单位:paramutc_time:utc时间戳,类似于1464830584:return:返回计算出的秒数"""t=datetime.datetime.fromtimestamp(int(utc_time))returnt。hour*3600+t.minute*60+t.secondefget_today_start_time():"""获取一天的开始时间"""dt=datetime.datetime.combine(datetime.date.today(),datetime.time.min)returndt.strftime('%Y-%m-%d%H:%M:%S')defget_today_end_time():"""获取一天的结束时间"""dt=datetime.datetime.combine(datetime.date.today(),datetime.time.max)返回dt.strftime('%Y-%m-%d%H:%M:%S')defget_final_day_of_current_week():"""获取本周的最后一天:星期日"""today=datetime.date.today()sunday=today+datetime.timedelta(6-today.weekday())returnsunday.strftime('%Y-%m-%d')defget_final_day_of_current_month():"""获取该月的最后一天"""today=datetime.date.today()_,last_day_num=calendar.monthrange(today.year,today.month)last_day=datetime.date(today.year,today.month,last_day_num)返回last_day.strftime('%Y-%m-%d')defget_final_day_of_last_month():"""获取上个月的最后一天,可能是新年,需要使用timedelta"""today=datetime.date.today()first=datetime.date(day=1,month=today.month,year=today.year)final_day_of_last_month=first-datetime.timedelta(days=1)returnfinal_day_of_last_month.strftime('%Y-%m-%d')defget_final_day_of_current_month(年,月):"""获取指定年份中指定月份的最后一天"""_,last_day_num=calendar.monthrange(year,month)returnlast_day_num#last_day=datetime.date(year,month,last_day_num)#returnlast_day.strftime('%Y-%m-%d')记得给我点赞哦!对计算机各个方向的视频课程和电子书,从入门、进阶、实用进行了认真梳理,并按照目录进行合理分类。你总能找到你需要的学习资料。你在等什么?立即关注并下载!!!念念不忘,必有回响,朋友们,点个赞吧,非常感谢职场亮哥,YY资深软件工程师,四年工作经验,不服的斜杠程序员成为领导者。听我说,我进步很大。如果有幸帮到你,请给我一个【点赞】,给我一个关注,如能评论鼓励,将不胜感激。职场凉阁文章列表:更多文章我的所有文章和回答均与版权保护平台合作,版权归职场凉阁所有。未经授权转载必究!