python处理时间【time、datetime、calendar、dateutil 、timezone等】

前言

趁着国庆假期,把python中的关于时间、日期、日历的几个模块深入研究研究,一直以来都是模模糊糊。


一、关于时间&日期中的几个概念与理论知识介绍

  • UNIX时间纪元:

UNIX系统认为1970年1月1日0点是时间纪元,所以我们常说的UNIX时间戳是以1970年1月1日0点为计时起点时间的(英国时间),最初计算机操作系统是32位,而时间也是用32位表示。32位能表示的最大值是2147483647。另外1年365天的总秒数是31536000,2147483647/31536000 = 68.1,也就是说32位能表示的最长时间是68年,而实际上到2038年01月19日03时14分07秒,便会到达最大时间,过了这个时间点,所有32位操作系统时间便会变为1000000000000000 0000000000000000,也就是1901年12月13日20时45分52秒,这样便会出现时间回归的现象,很多软件便会运行异常了。到这里,我想问题的答案已经出来了:因为用32位来表示时间的最大间隔是68年,而最早出现的UNIX操作系统考虑到计算机产生的年代和应用的时限综合取了1970年1月1日作为UNIXTIME的纪元时间(开始时间),至于时间回归的现象相信随着64为操作系统的产生逐渐得到解决,因为用64位操作系统可以表示到292,277,026,596年12月4日15时30分08秒。

  • 时区(UTC):

现今全球共分为24个时区(东、西各12个时区)。规定英国(格林尼治天文台旧址)为中时区(零时区)、东1—12区,西1—12区。每个时区横跨经度15度,时间正好是1小时。最后的东、西第12区各跨经度7.5度,以东、西经180度为界。每个时区的中央经线上的时间就是这个时区内统一采用的时间,称为区时,相邻两个时区的时间相差1小时。

  • 闰年(Leap Year):

闰年是历法中的名词,分为普通闰年和世纪闰年。 闰年(Leap Year)是为了弥补因人为历法规定造成的年度天数与地球实际公转周期的时间差而设立的。补上时间差的年份为闰年。闰年共有366天(1月~12月分别为31天、29天、31天、30天、31天、30天、31天、31天、30天、31天、30天、31天)。
1582年以来的置闰规则:
普通闰年:公历年份是4的倍数,且不是100的倍数的,为闰年(如2004年、2020年等就是闰年)。
世纪闰年:公历年份是整百数的,必须是400的倍数才是闰年(如1900年不是闰年,2000年是闰年)。
1582年以前的惯例:四年一闰;如果公元A年的A(正数)能被4整除,那么它就是闰年;如果公元前B年的B(正数)除以4余1,那么它也是闰年。

  • 公元(格里高利历、西元):

公元,是纪年法称谓,为纪年体系。该纪年法是以耶稣诞生为公元元年,公元元年之前的称公元前。所谓的2021年就是从公元元年开始算起的两千零二十一年。
python中即从0001-1-1 开始计算:Construct a date from a proleptic Gregorian ordinal. January 1 of year 1 is day 1. Only the year, month and day are non-zero in the result.

  • python中对时间的三种表示方法:

秒级时间戳:UninX时间纪元(1970-1-1 0:0:0)开始,到某个时间点的总的秒数,用一个整数表示时间。

格式化的时间字符串:人们易懂、通俗的描述方式。例如:2021-10-6、2021/10/6 12:30:30等。

struct_time类型的元组时间:struct_time(tm_year=2021, tm_mon=10, tm_mday=6, tm_hour=14, tm_min=30, tm_sec=50, tm_wday=3, tm_yday=256, tm_isdst=0),九个参数组成的元组。

  • python中关于时间定义的几个界限值介绍:

年份:year (1-9999) ---->minday=1, maxday=3652059
月份:month (1-12)
日期:day (1-31)
小时:hour (0-23)
分钟:minute (0-59)
秒钟:second (0-59)
微秒:microsecond (0-999999)

月份全称:January、February、March、April、May、June、July、August、September、October、November、December
月份简称:Jan、Feb、Mar、Apr、May、Jun、Jul、Aug、Sep、Oct、Nov、Dec
星期全称:Monday、Tuesday、Wednesday、Thursday、Friday、Saturday、Sunday
星期简称:Mon、Tue、Wed、Thu、Fri、Sat、Sun

weekday,通常一星期第一天从周一开始,标记为0::Return day of the week, where Monday == 0 … Sunday == 6.
isoweekday, ISO一星期从周一开始,标记为1:Return day of the week, where Monday == 1 … Sunday == 7.

二、python中time、datetime、calendar、dateutil 、timezone几个模块的关系介绍

在这里插入图片描述

三、python中time介绍

1.time模块日期格式转换的三角关系图

在这里插入图片描述
该图来源于网络:https://www.jb51.net/article/49326.htm

2.API汇总

API&返回值描述
localtime(secs: float | None = ...) -> struct_time: ...time.localtime()  # 返回当前时间的 struct_time类型
time.localtime(54555552) # 返回指定时间戳的 struct_time类型
gmtime(secs: float | None = ...) -> struct_time: ...time.gmtime() #返回 0 时区 时间 的 struct_time类型
time.gmtime(54555552) # 返回指定时间戳的 0 时区 struct_time类型
time() -> float: ...time.time() # 返回当前时间点时间戳,秒
mktime(t: _TimeTuple | struct_time) -> float: ...time.mktime(time.localtime()) #将 struct_time类型时间转换为时间戳
sleep(secs: float) -> None: ...#线程休眠时间(等待时间)
clock: () -> floattime.clock(), 第一次#返回线程执行时间;
第二次#返回距离上次time.clock()到本次time.clock()执行时间,第三次等
asctime(t: _TimeTuple | struct_time = ...) -> str: ...time.asctime() #将struct_time类型时间转换为固定字符串:Wed Oct  6 20:25:12 2021
time.asctime(time.localtime(54555552)) #将指定的struct_time类型时间转换为字符串
ctime: (secs: float | None = ...) -> strtime.ctime() #将当前时间点时间戳转换为字符串;为空,默认为 time.time()
time.ctime(1232222) #将指定时间戳转换为字符串
strftime(format: str, t: _TimeTuple | struct_time = ...) -> str: ...time.strftime('%Y-%m-%d %H:%M:%S')#将一个 struct_time类型时间转换为指定格式的字符串时间,若为空,则默认为time.localtime()
time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1212121212))#将一个 struct_time类型时间转换为指定格式的字符串时间
strptime(string: str, format: str = ...) -> struct_time: ...time.strptime('2021-10-6','%Y-%m-%d') #将字符串时间转换为 struct_time类型时间
get_clock_info(name: str) -> SimpleNamespace: ...
monotonic() -> float: ...
perf_counter() -> float: ...
process_time() -> float: ...
ctime(secs: float | None = ...) -> str: ...

3.API应用介绍

time模块应用代码例:

import time

# Python的time模块实现主要调用C库, 
# time模块, VSCode集成解释性pyi文件,指导开发

print(time.localtime()) # 返回当前时间的 struct_time类型
print(time.localtime(54555552)) # 返回指定时间戳的 struct_time类型

print(time.gmtime()) #返回 0 时区 时间 的 struct_time类型
print(time.gmtime(54555552)) # 返回指定时间戳的 0 时区 struct_time类型

print(time.time()) # 返回当前时间点时间戳,秒

print(time.mktime(time.localtime())) #将 struct_time类型时间转换为时间戳

print("wait 10s! ...")
time.sleep(10) #线程休眠时间(等待时间)
print("go on ... ")

print("thread all time: %s" %time.clock()) #返回线程执行时间
time.sleep(10)
print("thread all2 time: %s" %time.clock())#返回距离上次time.clock()到本次time.clock()执行时间

print(time.asctime()) #将struct_time类型时间转换为固定字符串:Wed Oct  6 20:25:12 2021
print(time.asctime(time.localtime(54555552))) #将指定的struct_time类型时间转换为字符串

print(time.ctime()) #将当前时间点时间戳转换为字符串;为空,默认为 time.time()
print(time.ctime(1232222)) #将指定时间戳转换为字符串

print(time.strftime('%Y-%m-%d %H:%M:%S')) #将一个 struct_time类型时间转换为指定格式的字符串时间,若为空,则默认为time.localtime()
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1212121212))) #将一个 struct_time类型时间转换为指定格式的字符串时间

print(time.strptime('2021-10-6','%Y-%m-%d')) #将字符串时间转换为 struct_time类型时间

time.struct_time()

三、python中datetime模块中time

1.python中 datetime.time API介绍

API参数返回值类型描述
__new__(cls, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)实例化timereturn self类静态方法,构造器实例化时间
d_t = time(23, 59, 59, 999999,None)
replace(self, hour=None, minute=None, second=None, microsecond=None,
                tzinfo=True)
return time普通方法返回新时间类型,
d_t_new = d_t.replace(14, 30,20,8000, None)
hourreturn hour (0-23)@propertyd_t_hour = d_t.hour
minutereturn minute (0-59)@propertyd_t_minute = d_t.minute
secondreturn second (0-59)@propertyd_t_second = d_t.second
microsecondreturn microsecond (0-999999)@propertyd_t_microsecond = d_t.microsecond
tzinforeturn timezone info object@propertyd_t_tzinfo = d_t.tzinfo
utcoffset(self)return UTC普通方法返回时间的时区
d_t_utc =d_t.utcoffset()
tzname(self)return the timezone name普通方法返回时间的时区名称
d_t_tzname =d_t.tzname()
dst(self)return dst;
夏令时:0 否; 1 是
普通方法返回是否夏令时
d_t_dst =d_t.dst()
isoformat(self)return the time formatted according to ISO.普通方法转换时间为ISO Str格式:'HH:MM:SS.mmmmmm+zz:zz', or 'HH:MM:SS+zz:zz'
d_t_iso = d_t.isoformat()
strftime(self, fmt)fmt格式return str普通方法格式化时间为字符串,格式:fmt
d_t_str = d_t.strftime('%H:%M:%S')

2.python中 datetime.time 应用示例

# -*- coding:utf-8 -*-

#时间
from datetime import time

# time.min = time(0, 0, 0)
# time.max = time(23, 59, 59, 999999)
# time.resolution = timedelta(microseconds=1)

d_time = time(23, 59, 59, 99999, None)
print(d_time)

d_hour = d_time.hour
print(d_hour)

d_minute = d_time.minute
print(d_minute)

d_second = d_time.second
print(d_second)

d_microsecond = d_time.microsecond
print(d_microsecond)

d_tzinfo = d_time.tzinfo
print(d_tzinfo)

d_isoformat = d_time.isoformat()
print("data: %s, dataType:%s" %(d_isoformat, str(type(d_isoformat))))

d_strftime = d_time.strftime("%H:%M:%S")
print(d_strftime)

d_utcoffset = d_time.utcoffset() #return UTC
print(d_utcoffset)

d_tzname = d_time.tzname() #return UTC Name
print(d_tzname)

d_dst = d_time.dst() #返回夏令时
print(d_dst)

d_replace = d_time.replace(14, 30)
print(d_replace)

四、python中datetime模块中date

1.python中 datetime.date API介绍

API参数返回值类型描述
__new__(cls, year, month=None, day=None)实例化datereturn self类静态方法,构造器实例化date: d = date(2021, 10, 6)
fromtimestamp(cls, t)t:Unix元年(1970-1-1)开始,时间戳return cls(y, m, d)@classmethod根据时间戳转化date:
d = date.fromtimestamp(7)
today(cls)return cls.fromtimestamp(t)@classmethod获取今日日期:
d = date.today()
fromordinal(cls, n)n:天数;
#从0001-1-1开始计算,将天数转换为日期,
0(MINYEAR = 1)<n<3652060(MAXYEAR = 9999/_MAXORDINAL = 3652059)
return cls(y, m, d)@classmethod将十进制天数转换为日期,公元算法
d =date.fromordinal(1)

相反方法:num = d.toordinal()
replace(self, year=None, month=None, day=None)替换为新日期类型return date(year, month, day)普通方法更改当前日期类型:
d_new = d.replace(2021,10,30)
ctime(self)return ctime() style string.普通方法date转换为str,格式:Wed Oct  6 00:00:00 2021
d_str = d.ctime()
strftime(self, fmt)fmt:格式化日期return string普通方法date格式化为字符串,格式:2021-10-06
d_str_fmt = d.strftime('%Y/%m/%d')
isoformat(self)return ISO date string普通方法date格式化为iso格式字符串,格式:'YYYY-MM-DD'
d_str_iso = d.isoformat()
yearreturn year (1-9999)@property返回年份
d_year = d.year
monthreturn month (1-12)@property返回月份
d_month = d.month
dayreturn day (1-31)@property返回天
d_day = d.yday
weekday(self)Return day of the week, where Monday == 0 ... Sunday == 6普通方法返回星期几,Monday == 0 ... Sunday == 6
d_week = d.weekday()
isoweekday(self)Return day of the week, where Monday == 1 ... Sunday == 7普通方法返回ISO星期几,Monday == 1 ... Sunday == 7
d_week = d.isoweekday()
isocalendar(self)Return a 3-tuple containing ISO year, week number, and weekday普通方法返回ISO年份、今年来的第几个星期,星期几
d_isocalendar = d.isocalendar()
timetuple(self)分割日期return (self._year, self._month, self._day,0, 0, 0, -1)普通方法返回 time.struct_time对象
d_struct_time = d.timetuple()
toordinal(self)return _ymd2ord(self._year, self._month, self._day)普通方法将日期转换为天数,公元算法(0001.01.01开始)
d_timestamp = d.toordinal()

2.datetime.date API应用代码示例:

# -*- coding:utf-8 -*-

#日期
from datetime import date

d_fromtimestamp = date.fromtimestamp(738069) #根据时间戳转换日期,从Unix纪元:1970-1-1开始
print(d_fromtimestamp)

d_today = date.today() #获取今天日期
print(d_today)

#从0001-1-1开始计算,将天数转换为日期, 0(MINYEAR = 1)<n<3652059(MAXYEAR = 9999/_MAXORDINAL = 3652059)
d_fromordinal = date.fromordinal(738069) 
print(d_fromordinal) #return 9999-12-31

d_new_date = date(2021, 10, 6)
print(d_new_date)

d_ctime = d_today.ctime() #Conversions(转换) to string
print(d_ctime)
print("data:%s,dataType:%s" %(d_ctime, str(type(d_ctime))))

d_strftime = d_today.strftime('%Y/%m/%d')  #格式化日期
print("data:%s,dataType:%s" %(d_strftime, str(type(d_strftime))))

d_isoformat = d_today.isoformat()
print("data:%s,dataType:%s" %(d_isoformat, str(type(d_isoformat)))) #转换为 ISO格式:This is 'YYYY-MM-DD'.

d_year = d_today.year  # @property修饰的方法,以属性值访问
print("data:%s,dataType:%s" %(d_year, str(type(d_year))))

d_month = d_today.month
print("data:%s,dataType:%s" %(d_month, str(type(d_month))))

d_day = d_today.day
print("data:%s,dataType:%s" %(d_day, str(type(d_day))))

d_timetuple = d_today.timetuple()
print("data:%s,dataType:%s" %(d_timetuple, str(type(d_timetuple))))

d_toordinal = d_today.toordinal()
print("data:%s,dataType:%s" %(d_toordinal, str(type(d_toordinal))))

d_replace = d_today.replace(year=2022, month=11, day=24)
print(d_replace)

d_weekday = d_today.weekday()
print(d_weekday) #Return day of the week, where Monday == 0 ... Sunday == 6.

d_isoweekday = d_today.isoweekday()
print(d_isoweekday)#Return day of the week, where Monday == 1 ... Sunday == 7.

d_isocalendar = d_today.isocalendar()
print(d_isocalendar)

days = d_today.toordinal() - date(2021, 1, 1).toordinal()
print(days)
print(days/7)

五、python中datetime模块中datetime

1.python中 datetime.datetime API介绍

API参数返回值类型描述
__new__(cls, year, month=None, day=None, hour=0, minute=0, second=0,
                microsecond=0, tzinfo=None):
return self类静态方法,构造器实例化datetime:
dt = datetime(2021,10,6,23, 59, 59, 999999,None)
fromtimestamp(cls, t, tz=None)t:时间戳、
tz:时区,默认取值None,当前时区
return datetime @classmethod返回默认时区的datetime:
dt = datetime.fromtimestamp(t, tz=None)
utcfromtimestamp(cls, t)t:时间戳、
return datetime @classmethod返回0时区、英国-格林尼治时间(UTC±0)datetime:
dt = datetime.utcfromtimestamp(t)
now(cls, tz=None)return datetime @classmethod返回现在datetime时间:
dt = datetime.now()
utcnow(cls)return datetime @classmethod返回现在datetime时间,0时区、英国-格林尼治时间(UTC±0):
dt = datetime.utcnow()
combine(cls, date, time)date:日期
time: 时间
return datetime @classmethod拼接date和time,返回datetime:
dt = datetime(date, time)
replace(self, year=None, month=None, day=None, hour=None,
                minute=None, second=None, microsecond=None, tzinfo=True)
return datetime普通方法返回一个新的datetime类型:
dt_new = dt.replace(2021,10,6, [...])
yearclass datetime(date)return year (1-9999) @propertydt_year = dt.year
monthreturn month (1-12) @propertydt_month = dt.month
dayreturn day (1-31) @propertydt_day = dt.day
hourreturn hour (0-23) @propertydt_hour = dt.hour
minutereturn minute (0-59) @propertydt_minute = dt.minute
secondreturn second (0-59) @propertydt_second = dt.second
microsecondreturn microsecond (0-999999) @propertydt_microsecond = dt.microsecond
tzinforeturn timezone info object @propertydt_tzinfo = dt.tzinfo
date(self)return date普通方法返回 date:
dt_d = dt.date()
time(self)return time普通方法返回 time:
dt_t = dt.time()
timetz(self)return the time part, with same tzinfo普通方法返回相同时区一个time,return time:
dt_t = dt.timez()
utcoffset(self)普通方法返回时间区
tzname(self)普通方法返回时间区名字
dst(self)普通方法返回时间区夏令时
timetuple(self)return struct_time(self.year, self.month,
self.day,self.hour, self.minute, self.second,dst)
普通方法拆分datime:
dt_struct_time = dt.timetuple()
utctimetuple(self)return struct_time(y, m, d, hh, mm, ss, 0)普通方法拆分datime,按照0时区进行解析:
dt_struct_time = dt.timetuple()
timestamp(self)return POSIX timestamp as float普通方法返回时间戳(秒):
dt_timestamp = dt.timestamp()
astimezone(self, tz=None)普通方法设置时区
ctime(self)return str普通方法转换datetime为字符串:
dt_str = dt.ctime()
isoformat(self, sep='T')return the time formatted according to ISO普通方法转换datetime为字符串,以T隔开:
dt_str = dt.isoformat( sep='T')
strptime(cls, date_string, format)string, format -> new datetime parsed from a string @classmethod将字符串转换为datetime类型:
dt = datetime.strptime("2021-1-6 6:30:30", "%Y-%m-%d %H:%M:%S")

2.python中 datetime.datetime API代码示例

# -*- coding:utf-8 -*-

"""year (1-9999)"""
"year -> 1 if leap year, else 0."
"""month (1-12)"""
"""day (1-31)"""
(MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7)
"""hour (0-23)"""
"""minute (0-59)"""
"""second (0-59)"""
"""microsecond (0-999999)"""
"""timezone info object: tzinfo=timezone.utc"""
"""UNIX系统认为1970年1月1日0点是时间纪元,所以我们常说的UNIX时间戳是以1970年1月1日0点为计时起点时间的(英国时间),
最初计算机操作系统是32位,而时间也是用32位表示。32位能表示的最大值是2147483647。另外1年365天的总秒数是31536000,2147483647/31536000 = 68.1,也就是说32位能表示的最长时间是68年,而实际上到2038年01月19日03时14分07秒,便会到达最大时间,过了这个时间点,所有32位操作系统时间便会变为10000000 00000000 00000000 00000000,也就是1901年12月13日20时45分52秒,这样便会出现时间回归的现象,很多软件便会运行异常了。
到这里,我想问题的答案已经出来了:因为用32位来表示时间的最大间隔是68年,而最早出现的UNIX操作系统考虑到计算机产生的年代和应用的时限综合取了1970年1月1日作为UNIX TIME的纪元时间(开始时间),至于时间回归的现象相信随着64为操作系统的产生逐渐得到解决,因为用64位操作系统可以表示到292,277,026,596年12月4日15时30分08秒
"""

import datetime, pytz

#时区
"""
tzinfo是关于时区信息的类
tzinfo是一个抽象类,所以不能直接被实例化
https://www.cnblogs.com/goodspeed/archive/2011/11/07/python_tzinfo.html
"""
class UTC(datetime.tzinfo):
    """UTC"""
    def __init__(self,offset = 0):
        self._offset = offset

    def utcoffset(self, dt):
        return datetime.timedelta(hours=self._offset)

    def tzname(self, dt):
        return "UTC +%s" % self._offset

    def dst(self, dt):
        return datetime.timedelta(hours=self._offset)
tz = UTC(0)
tz = None
print(tz)

dt = datetime.datetime.fromtimestamp(0, tz) #默认本地时区
print("dt | %s" %dt)
print(dt.hour)
print(dt.minute)
print(dt.second)
print(dt.microsecond)
print(dt.tzinfo)

dt_utc = datetime.datetime.utcfromtimestamp(0) # 0时区、英国-格林尼治时间(UTC±0)
print("dt_utc | %s" %dt_utc)

dt_now = datetime.datetime.now() #获取当地现在时间,默认utc=None;也可以指定utc
print(dt_now)

dt_utc_now = datetime.datetime.utcnow() # 0时区、英国-格林尼治时间(UTC±0)
print(dt_utc_now)

date = datetime.date.today()
time = datetime.time(0, 0, 0)
dt_combine = datetime.datetime.combine(date, time) #构造 date和time组合datetime对象
print("----------------------------------------------------------------------")
print(dt_combine)
print("----------------------------------------------------------------------")

#实例化对象
dt_utc_now = datetime.datetime.utcnow() # 0时区、英国-格林尼治时间(UTC±0)
print(dt_utc_now)
# 实例化对象调用方法
dt_timetuple = dt_utc_now.timetuple() #拆分datetime
print(dt_timetuple)
'''time.struct_time(
    tm_year=2021, tm_mon=10, tm_mday=5, 
    tm_hour=5, tm_min=57, tm_sec=52, 
    tm_wday=1, tm_yday=278, tm_isdst=-1)  
tm_isdst:DST 是daylight saving time, 意思是:夏令时
tm_isdst = 1 的时候表示时间是夏令时,
值为0的时候表示非夏令时
值为-1的时候表示时间不确定是否是夏令时
'''
dt_utctimetuple = dt_utc_now.utctimetuple()
print(dt_utctimetuple)

dt_timestamp = dt_utc_now.timestamp() #返回时间戳
print(dt_timestamp)

dt_date = dt_now.date() #返回日期
print(dt_date)

dt_time = dt_now.time() #返回默认时区的时间,
print(dt_time)

dt_timetz = dt_now.timetz() #返回相同时区的时间
print(dt_timetz)

dt_replace = dt_now.replace( year=2020, month=12) #修改datetime对象
print(dt_replace)

#报错:ValueError: astimezone() cannot be applied to a naive datetime
# dt_astimezone = dt_utc_now.astimezone(pytz.timezone("Asia/Kolkata")) #时区间借助模块去实例化:pytz
# print(dt_astimezone)

dt_ctime = dt_now.ctime() #返回欧美时间格式 Tue Oct  5 14:27:02 2021
print(dt_ctime)

dt_isoformat = dt_now.isoformat() #返回 ISO格式的时间
print(dt_isoformat)

dt_now_str = datetime.datetime.strptime("2021-1-6 6:30:30", "%Y-%m-%d %H:%M:%S")
print(dt_now_str)

五、python中datetime模块之timedelta

1.python中datetime模块之timedelta API介绍

API参数返回值类型描述
__new__(cls, days=0, seconds=0, microseconds=0,
                milliseconds=0, minutes=0, hours=0, weeks=0)
表示两个datetime、date之间的差异的对象
total_seconds(self)获取所有秒
days@property总天数
seconds@property总秒数
microseconds@property总微秒
datetime.datetime.now() - datetime.timedelta(days = 100),计算100天前的日期;

关于该模块,图片来源于博客:https://www.cnblogs.com/fengff/p/9021117.html
在这里插入图片描述

2.python中datetime模块之timedelta API代码示例

代码来源于:https://www.cnblogs.com/fengff/p/9021117.html

# 爱学习,爱鱼C工作室
>>> from datetime import timedelta
>>> year = timedelta(days=365)
>>> another_year = timedelta(weeks=40, days=84, hours=23,
...                          minutes=50, seconds=600)  # adds up to 365 days
>>> year.total_seconds()
31536000.0
>>> year == another_year
True
>>> ten_years = 10 * year
>>> ten_years, ten_years.days // 365
(datetime.timedelta(3650), 10)
>>> nine_years = ten_years - year
>>> nine_years, nine_years.days // 365
(datetime.timedelta(3285), 9)
>>> three_years = nine_years // 3;
>>> three_years, three_years.days // 365
(datetime.timedelta(1095), 3)
>>> abs(three_years - ten_years) == 2 * three_years + year
True

六、python中datetime模块之timezone

1.python中datetime模块之timezone API介绍

不做详细的API梳理,重点关注时区的切换,具体见博客:https://www.it610.com/article/1296084575969157120.htm

2.python中datetime模块之timezone API代码示例

#! /usr/bin/python
# coding=utf-8

from datetime import datetime, tzinfo,timedelta

"""
tzinfo是关于时区信息的类
tzinfo是一个抽象类,所以不能直接被实例化
"""
class UTC(tzinfo):
    """UTC"""
    def __init__(self,offset = 0):
        self._offset = offset

    def utcoffset(self, dt):
        return timedelta(hours=self._offset)

    def tzname(self, dt):
        return "UTC +%s" % self._offset

    def dst(self, dt):
        return timedelta(hours=self._offset)

#北京时间
beijing = datetime(2011,11,11,0,0,0,tzinfo = UTC(8))
print "beijing time:",beijing
#曼谷时间
bangkok = datetime(2011,11,11,0,0,0,tzinfo = UTC(7))
print "bangkok time",bangkok
#北京时间转成曼谷时间
print "beijing-time to bangkok-time:",beijing.astimezone(UTC(7))

#计算时间差时也会考虑时区的问题
timespan = beijing - bangkok
print "时差:",timespan

#Output==================
# beijing time: 2011-11-11 00:00:00+08:00
# bangkok time 2011-11-11 00:00:00+07:00
# beijing-time to bangkok-time: 2011-11-10 23:00:00+07:00
# 时差: -1 day, 23:00:00
from datetime import datetime, timezone, timedelta


# 构造 timezone(offset, name=None)
china_tz = timezone(timedelta(hours=8))
china_tz = timezone(timedelta(hours=8), 'Asia/Shanghai')


# 类属性
print(timezone.utc)         # utc 时区
print(timezone.min)         # UTC-23:59
print(timezone.max)         # UTC+23:59


# 方法
dt = datetime.now(china_tz)
print(china_tz.tzname(dt))      # Asia/Shanghai
print(china_tz.utcoffset(dt))   # 8:00:00
print(china_tz.dst(dt))         # None
print(china_tz.fromutc(dt))     # 2018-09-23 14:55:48.107650+08:00

七、python中calendar模块

1.python中 calendar模块 API介绍

API实际调用的方法参数类型描述
isleap(year)SAMEyear:年份模块方法:calendar.isleap(year)返回是否瑞年
leapdays(y1, y2)SAMEY1到Y2年份之间年份模块方法:calendar.leapdays(y1, y2)返回瑞年数量
weekday(year, month, day)SAME模块方法:calendar.weekday(year, month, day)返回星期几
monthrange(year, month)SAME模块方法:calendar.monthrange(year, month)返回当前月份有几个星期&当月天数
setfirstweekday(firstweekday)SAMEfirstweekday int模块方法:calendar.setfirstweekday(firstweekday)设置一个星期第一天
firstweekday()SAME模块方法:calendar.monthrange(year, month)获取一个星期第一天
calendar.monthcalendar(year, month)monthdayscalendar(self, year, month)year、month返回当前月份星期
calendar.prmonth(year, month, l, w)prmonth(self, theyear, themonth, w=0, l=0)year、month、w、l返回当前月份日历
calendar.month(year, month, w, l)formatmonth(self, theyear, themonth, w=0, l=0)year、month、w、l返回当前月份日历
calendar.prcal(year, w, l, c, m)pryear(self, theyear, w=0, l=0, c=6, m=3)year、month、w、l返回当前月份日历
calendar.calendar(year, c, l, w)formatyear(self, theyear, w=2, l=1, c=6, m=3)w:日期列宽、l:日期行高、c:每个月之间的间隔宽度 、m:显示列返回当前年份日历
timegm(tuple)SAMEyear, month, day, hour, minute, second = tuple[:6]返回时间戳
calendar.month_nameAttr获取月份名称
calendar.month_abbrAttr获取月份名称简称
calendar.day_nameAttr获取星期名称
calendar.day_abbrAttr获取星期简称

2.python中 calendar模块 API介绍

# -*- coding:utf-8 -*-

import calendar
#calendar 基于datetime date实现的

ca_isleap = calendar.isleap(2020) #返回是否瑞年
print(ca_isleap)

ca_isleaps = calendar.leapdays(2020, 2030) #返回瑞年数量
print(ca_isleaps)

ca_weekday = calendar.weekday(2021, 10, 6) #返回星期几
print(ca_weekday)

ca_monthrange =  calendar.monthrange(2021, 10) #返回当前月份有几个星期&当月天数
print(ca_monthrange)

ca_setfirstweekday = calendar.setfirstweekday(1) # 0 = Monday, 6 = Sunday
print(ca_setfirstweekday)

print(calendar.firstweekday())

print("-----------------------------------------------------------------")
ca_obj = calendar.TextCalendar(firstweekday=0)
ca_text = ca_obj.monthdayscalendar(2021,10)
print(ca_text)
print(calendar.monthcalendar(2021, 10)) #当月星期数

ca_prmonth = ca_obj.prmonth(2021, 10, l=2, w=6)
print(ca_prmonth)
print(calendar.prmonth(2021, 10, l=2, w=5)) #返回当月日历

ca_month = ca_obj.formatmonth(2021, 10, w=12, l=2)
print(ca_month)
print(calendar.month(2021, 10, w=5, l=2)) #返回当月日历

ca_prcal = calendar.prcal(2021, w=3, l=0, c=12, m=3) #w:日期列宽、l:日期行高、c:每个月之间的间隔宽度 、m:显示列
print(ca_prcal)

ca_calendar = calendar.calendar(2021, c=12, l=0, w=3)
print(ca_calendar)

# print("************************************************")
# #year, month, day, hour, minute, second = tuple[:6]
ca_timegm = calendar.timegm((2021, 10, 6, 0, 59, 30)) #返回时间戳
print(ca_timegm)

# print("************************************************")
ca_month_name = calendar.month_name #输出月份名字
for ca in ca_month_name:
    print(ca)

# print("************************************************")
ca_month_abbr = calendar.month_abbr #输出月份简称
for ca in ca_month_abbr:
    print(ca)

# print("************************************************")
ca_day_name = calendar.day_name #输出星期名称
for ca in ca_day_name:
    print(ca)

# print("************************************************")
ca_day_abbr = calendar.day_abbr #输出星期简称
for ca in ca_day_abbr:
    print(ca)

总结

提示:这里对文章进行总结:
例如:以上就是今天要讲的内容,本文仅仅简单介绍了pandas的使用,而pandas提供了大量能使我们快速便捷地处理数据的函数和方法。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值