layout: posttitle: Python时间和日期操作
subtitle: datetime Arrow
date: 2019-12-18
author: NSX
header-img: img/post-bg-ios9-web.jpg
catalog: true
tags:
- 技术
- Python
- 教程
Python时间和日期操作
Python中,对日期和时间的操作,主要使用这3个内置模块: datetime 、 time 和 calendar
导入需要的包
import arrowimport time, calendarfrom datetime import datetime
获取当前时间
str(datetime.now())
获取两个代码位置在执行时的时间差
before = time.time()func1()after = time.time()print(f’调用func1,花费时间{before-after}’)
格式化日期(指定输出的时间格式)
dayTime=('2018-01-14 12:00:00')dayTime1= datetime.strptime(dayTime,'%Y-%m-%d %a %H:%M:%S').strftime("%w")dayTime2= datetime.datetime(2018,1,14).strftime("%w")# 格式化成2016-03-20 11:45:39形式print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())# 格式化成Sat Mar 28 22:24:24 2016形式print time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())
数字表示的时间转化为字符串表示
time.strftime('%Y%m%d %H:%M:%S',time.localtime(1434502529))
获得指定时间字符串对应星期几
thatDay = "2018-6-24"week = datetime.strptime(thatDay,'%Y-%m-%d').strftime("%w")# week= datetime.datetime(2018,6,24).strftime("%w")
Arrow 介绍
arrow是一个提供了更易懂和友好的方法来创建、操作、格式化和转化日期、时间和时间戳的python库。可以完全替代datetime,支持python2和3
基本使用
以当前时间获取arrow对象
import arrow>>> cur = arrow.now()>>> cur<Arrow [2017-02-04T13:47:58.114342+08:00]>>>> cur.timestamp>>> cur.year>>> cur.month>>> cur.day>>> cur.hour>>> cur.minute>>> cur.second>>> cur.week
以指定时间戳获取arrow对象
>>> arrow.get('1586782011')<Arrow [2020-04-13T12:46:51+00:00]>>>> arrow.get('2017-01-05')<Arrow [2017-01-05T00:00:00+00:00]>>>> arrow.get('2017.01.05')<Arrow [2017-01-05T00:00:00+00:00]>>>> arrow.get('2017/01/05')<Arrow [2017-01-05T00:00:00+00:00]>
时间的计算和移动shift
>>> utc.replace(days=1) # 设置日等于1号>>> utc.replace(hours=2) # 设置hour等于2点,取值为0-23>>> utc.replace(weeks=1) #>>> utc.shift(days=+1) # 1天之后>>> utc.shift(hours=-2) # 2小时之前>>> cur.shift(years=1) # 明年
PS:注意hour与hours的区别,前者是设置时间,后者是在原来时间的基础上加减
数据运算
Arrow对象可以通过简单的大于小于符合来判断时间先后,如:
>>> start = arrow.get('2017-02-03T15:47:58.114342+02:00')>>> end = arrow.get('2017-02-02T07:17:41.756144+02:00')>>> start<Arrow [2017-02-03T15:47:58.114342+02:00]>>>> end<Arrow [2017-02-02T07:17:41.756144+02:00]>>>> start > endTrue>>> start_to = start.to('+08:00')>>> start == start_toTrue
也可以通过’-‘运算符来获得时间的差值,如:
>>> start - enddatetime.timedelta(1, 30616, 358198)
转换为指定时间格式
arrow.now().format('YYYY-MM-DD HH:mm:ss ZZ')
附录: 时间格式说明
%a 星期几的简写 Weekday name, abbr.%A 星期几的全称 Weekday name, full%w 星期(0-6),星期天为星期的开始%W 一年中的星期数(00-53)星期一为星期的开始%b 月分的简写 Month name, abbr.%B 月份的全称 Month name, full%c 本地相应的日期表示和时间表示%x 本地相应的日期表示 (e.g. 13/01/08)%X 本地相应的时间表示 (e.g. 17:02:10)%H 24小时制的小时 Hour (24-hour clock)%M 十时制表示的分钟数 Minute number%S 十进制的秒数 Second number
