Python的日期时间模块大全

time时间模快

1、在time模块中,可以用三种表现形式来表示时间,分别是时间戳、格式化日期时间字符串和结构化日期时间:

1.1、时间戳time.time()

print(time.time())

>>> 1596522366.8774376

时间戳都以自从1970年1月1日午夜(历元)经过了多长时间来表示最适于做日期运算

1.2、格式化日期时间字符串time.strftime()

print(time.strftime('%Y-%m-%d %X'))

>>> 2020-14-08 14:30:57

%a 本地星期名称的简写
%A 本地星期名称的全称
%b 本地月份名称的简写
%B 本地月份名称的全称
%c 本地相应的日期表示和时间表示
%d 一个月中的第几天(01 - 31)
%f 微秒(范围0.999999)
%H 一天中的第几个小时(0-23)
%I 第几个小时(12小时制,01-12)
%j 一年中的第几天(001 - 366)
%m 月份(01 - 12)
%M 分钟数(00 - 59)
%p 本地A.M.或P.M的标识符
%S 秒数(00 - 59)
%U 一年中的星期数。(00 - 53星期天是一个星期的开始)
%w 一个星期中的第几天(0 - 6,0是星期天)
%W 和%U基本相同,不同的是%W以星期一为一个星期的开始。
%x 本地相应的日期表示
%X 本地相应的时间表示
%y 两位数的年份表示(00-99)
%Y 四位数的年份表示(000-9999)
%z 与UTC时间的间隔(如果是本地时间,返回空字符串)
%Z 时区的名字(如果是本地时间,返回空字符串)
%% %号本身

1.3、结构化日期时间或者叫时间元祖,通过time.localtime()获得

# time.localtime(time.time())
print(time.localtime())
>>> time.struct_time(tm_year=2020, tm_mon=8, tm_mday=4, tm_hour=14, tm_min=46, tm_sec=54, tm_wday=1, tm_yday=217, tm_isdst=0)
属性
tm_year
tm_mon
tm_mday
tm_hour
tm_min
tm_sec
tm_wday0到6 (0是周一)
tm_yday一年的第几天
tm_isdst是否是夏令时(-1, 0, 1, -1是决定是否为夏令时的旗帜)

2、time模块其他基本使用方法

#返回格林威治西部的夏令时地区的偏移秒数。如果该地区在格林威治东部会返回负值(如西欧,包括英国)。对夏令时启用地区才能使用。
time.altzone
# 接受时间元组并返回一个可读的形式为"Tue Dec 11 18:07:14 2008"(2008年12月11日 周二18时07分14秒)的24个字符的字符串
time.asctime([tupletime])
# 推迟调用线程的运行,t指秒数。
time.sleep(t)
# 用以浮点数计算的秒数返回当前的CPU时间。用来衡量不同程序的耗时,比time.time()更有用。
time.clock( )
# 作用相当于asctime(localtime(secs)),未给参数相当于asctime()
time.ctime([secs])
# 接收时间戳并返回格林威治天文时间下的时间元组t
time gmtime()
# 接受时间元组并返回时间戳,接收struct_time对象作为参数,返回用秒数来表示时间的浮点数
time.mktime(tupletime)
# 接收以时间元组,并返回以可读字符串表示的当地时间,格式由fmt决定。
time.strftime(fmt[,tupletime])
#是time.strftime()方法的逆向操作
time.strptime(str,fmt='%a %b %d %H:%M:%S %Y')
# 根据环境变量TZ重新初始化时间相关设置。 
time.tzset()

datatime模块

datetime模块提供了用于操作日期和时间的类。
虽然支持日期和时间算法,但实现的重点是为输出格式化和操作有效地提取属性。

1.time类

datetime.time(hour[ , minute[ , second[ , microsecond[ , tzinfo] ] ] ] )

import datetime

t = datetime.time(11, 12, 13)
print(t)  #time对象
print(t.hour)    # 时
print(t.minute)  # 分
print(t.second)  # 秒
print(t.microsecond)   # 微妙
print(t.microsecond)   # 时区
print(t.isoformat())   # 返回型如"HH:MM:SS"格式的字符串表示
print(t.strftime("%X"))   # 11:12:13

2、data类

datetime.date(year, month, day)

import datetime
print('date.max:', datetime.date.max)  # 表示的最大日期;
print('date.min:', datetime.date.min)  # 表示的最小日期;
print('date.resolution:', datetime.date.resolution)  # 表示日期的最小单位。这里是天 
print('date.today:', datetime.date.today())  # 表示当前本地日期的date对象
print('date.fromtimestamp:', datetime.date.fromtimestamp(time.time()))  # 根据给定的时间戮,返回一个date对象

today = datetime.date.today()
print(today)  #  年、月、日;
print(today.year) # 年
print(today.month) # 月
print(today.day)  # 日
print(today..timetuple())  # 返回日期对应的time.struct_time对象;
print(today.replace(year, month, day))  # 生成一个新的日期对象,用参数指定的年,月,日代替原有对象中的属性
print(today.weekday())  # 星期一,返回1;星期2,返回2
print(today.isocalendar())   # 返回格式如(year,month,day)的元组
print(today.isoformat())   # 返回格式如'YYYY-MM-DD’的字符串
oday.strftime("%Y")   # 2020

3、datetime类

datetime.datetime (year, month, day[ , hour[ , minute[ , second[ , microsecond[ , tzinfo] ] ] ] ] )

import datetime
# 返回一个表示当前本地时间的datetime对象;
print(datetime.datetime.today())
# 返回一个表示当前本地时间的datetime对象
print(datetime.datetime.now())
# 表示的最大日期时间
print(datetime.datetime.max)
# 表示的最小日期时间
print(datetime.datetime.min)
# 表示时间的最小单位
print(datetime.datetime.resolution)
# 返回一个当前utc时间的datetime对象;#格林威治时间
print(datetime.datetime.utcnow())
# 根据时间戮创建一个datetime对象
print(datetime.datetime.fromtimestamp(time.time()))
# 根据时间戮创建一个datetime对象
print(datetime.datetime.utcfromtimestamp(time.time()))
# 根据date和time,创建一个datetime对象;
print(datetime.datetime.combine(datetime.date.today(), datetime.time()))

4、timedelta类

用于时间的加减

now_time=datetime.datetime.now()
print(now_time.strftime("%Y-%m-%d %H:%M:%S"))
print((now_time+datetime.timedelta(days=- 10)).strftime("%Y-%m-%d %H:%M:%S")) #获取后一天
print(now_time.strftime("%Y-%m-%d %H:%M:%S"),(now_time+datetime.timedelta(minutes=+1)).strftime("%Y-%m-%d %H:%M:%S"))   #前一分钟后一分钟
print(now_time.strftime("%Y-%m-%d %H:%M:%S"),(now_time+datetime.timedelta(minutes=+1/60)).strftime("%Y-%m-%d %H:%M:%S"))#前一秒后一秒
print ((now_time+datetime.timedelta(hours=-1)).strftime("%Y-%m-%d %H:%M:%S")) #获取前一小时

5、tzinfo类

时差

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)


# 北京时间
beijing = datetime.datetime(2011, 11, 11, 0, 0, 0, tzinfo=UTC(8))
print("beijing time:", beijing)
# 曼谷时间
bangkok = datetime.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)

Calendar模块

日历, 星期一是默认的每周第一天,星期天是默认的最后一天。更改设置需调用calendar.setfirstweekday()函数。

# 返回一个多行字符串格式的year年年历,3个月一行,间隔距离为c。 每日宽度间隔为w字符。每行长度为21* W+18+2* C。l是每星期行数
print(calendar.calendar(2019,w=2,l=1,c=6))
# 返回当前每周起始日期的设置。返回0,即星期一。
print(calendar.firstweekday( ))
# 是闰年返回 True,否则为 false。
print(calendar.isleap(2008))
# 返回在两年之间的闰年总数
print(calendar.leapdays(2008, 2015))
# 返回某月的第一天是星期几和这个月的天数,星期几是从0(星期一)到 6(星期日)
print(calendar.monthrange(2020, 8))
# 返回一个多行字符串格式的year年month月日历,两行标题,一周一行。每日宽度间隔为w字符。每行的长度为7* w+6。l是每星期的行数。
print(calendar.month(2020, 8, w=2, l=1))
# 返回一个整数的单层嵌套列表。每个子列表装载代表一个星期的整数。Year年month月外的日期都设为0;范围内的日子都由该月第几日表示,从1开始。
print(calendar.monthcalendar(2020, 8))
# 相当于 print (calendar.calendar(year, w=0, l=0, c=6, m=3))
calendar.prcal(year, w=0, l=0, c=6, m=3)
# 相当于 print(calendar.month(theyear, themonth, w=0, l=0))。
calendar.prmonth(theyear, themonth, w=0, l=0)
# 设置每周的起始日期码。0(星期一)到6(星期日)。
calendar.setfirstweekday(weekday)
# 和time.gmtime相反:接受一个时间元组形式,返回该时刻的时间戳
calendar.timegm(tupletime)
# 返回给定日期的日期码。0(星期一)到6(星期日)。月份为 1(一月) 到 12(12月)
calendar.weekday(year,month,day)
  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值