python 关于时间的操作

python 关于时间的操作

1. 日期输出格式化

所有日期、时间的api都在datetime模块内。

  1. datetime => string
now = datetime.datetime.now()
now.strftime('%Y-%m-%d %H:%M:%S')
#输出2012-03-05 16:26:23.870105
strftime是datetime类的实例方法。
  1. string => datetime
#方法一
t_str = '2012-03-05 16:26:23'
d = datetime.datetime.strptime(t_str, '%Y-%m-%d %H:%M:%S')
strptime是datetime类的静态方法。

#方法二
t_str = '2012-03-05 16:26:23'
# 转换成时间数组
timeArray = time.strptime(dt, "%Y-%m-%d %H:%M:%S")
  1. 时间戳 => datetime
#方法一:
import time
time_now = int(time.time())
time_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time_now))
print(time_time)

#以上方法要转换的字符串中如果有汉字,则会报转码错误,方法二可解决

#方法二

time_now = 1566284145
time_time = time.strftime('%Y{y}%m{m}%d{d} %H:%M:%S', time.localtime(time_now)).format(y='年', m='月', d='日')
print(time_time)

  1. datetime=> 时间戳
dt ='2012-03-05 16:26:23'
# 转换成时间数组
timeArray = time.strptime(dt, "%Y-%m-%d %H:%M:%S")
# 转换成时间戳
timestamp = int(time.mktime(timeArray))
  1. 时间格式化输出
>>> print datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
2019-07-11 14:25:33
>>> print datetime.datetime.now().strftime("%Y%m%d%H%M%S")
20190711142533
>>> print datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
2019-07-11 14:25
2. 日期比较操作

在datetime模块中有timedelta类,这个类的对象用于表示一个时间间隔,比如两个日期或者时间的差别。

构造方法:

datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

所有的参数都有默认值0,这些参数可以是int或float,正的或负的。

可以通过timedelta.days、tiemdelta.seconds等获取相应的时间值。

timedelta类的实例,支持加、减、乘、除等操作,所得的结果也是timedelta类的实例。比如:

year = timedelta(days=365)
ten_years = year *10
nine_years = ten_years - year

同时,date、time和datetime类也支持与timedelta的加、减运算。

datetime1 = datetime2 +/- timedelta
timedelta = datetime1 - datetime2

这样,可以很方便的实现一些功能。

  1. 两个日期相差多少天。
#计算两个指定日期的间隔
d1 = datetime.datetime.strptime('2012-03-05 17:41:20', '%Y-%m-%d %H:%M:%S')
d2 = datetime.datetime.strptime('2012-03-02 17:41:20', '%Y-%m-%d %H:%M:%S')
delta = d1 - d2
print(delta.days)
输出:3
  1. 使用timedelta方法对当前时间进行加减。
#加 一分钟
>>> print (datetime.datetime.now()+datetime.timedelta(minutes=1)).strftime("%Y-%m-%d %H:%M:%S")
2019-07-11 14:29:46
#减 一分钟
>>> print (datetime.datetime.now()+datetime.timedelta(minutes=-1)).strftime("%Y-%m-%d %H:%M:%S")
2019-07-11 14:29:32
#加 一天
>>> print (datetime.datetime.now()+datetime.timedelta(days=1)).strftime("%Y-%m-%d %H:%M:%S")
2019-07-12 14:32:37
#加 一小时
>>> print (datetime.datetime.now()+datetime.timedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%S")
2019-07-11 15:33:37

使用timedelta方法,最大时间单位为周weeks,如果要加一个月,需使用到dateutil库

import datetime
from dateutil.relativedelta import relativedelta

print(datetime.date.today())
print(datetime.date.today() + relativedelta(months=1))
print(datetime.date.today() - relativedelta(months=-1)
2020-01-10
2020-02-10
2020-02-10

dateutil.relativedelta的构造方法

dateutil.relativedelta(dt1=None, dt2=None,
                 years=0, months=0, days=0, leapdays=0, weeks=0,
                 hours=0, minutes=0, seconds=0, microseconds=0,
                 year=None, month=None, day=None, weekday=None,
                 yearday=None, nlyearday=None,
                 hour=None, minute=None, second=None, microsecond=None)

可以加一个月,一年,或者指定年月日,指定时间。

arrow

第三方库Arrow提供了一个合理的、人性化的方法来创建、操作、格式转换的日期,时间,和时间戳,帮助我们使用较少的导入和更少的代码来处理日期和时间。

获取当前时间 arrow.utcnow(), arrow.now()

>>> arrow.utcnow()
<Arrow [2018-02-24T13:15:29.981135+00:00]>
>>> arrow.now()
<Arrow [2018-02-24T21:15:50.841056+08:00]>

将时间戳转化为arrow对象 arrow.get(timestamp)

>>> arrow.get(1519534533)
<Arrow [2018-02-25T04:55:33+00:00]>
 
>>> arrow.get('1519534533')
<Arrow [2018-02-25T04:55:33+00:00]>
 
>>> arrow.get(1519534533.153443)
<Arrow [2018-02-25T04:55:33.153443+00:00]>
 
>>> arrow.get('1519534533.153443')
<Arrow [2018-02-25T04:55:33.153443+00:00]>

时间戳可以是int,float或者可以转化为float的字符串

将字符串转换为arrow对象 arrow.get(string[,format_string])

>>> arrow.get('2018-02-24 12:30:45', 'YYYY-MM-DD HH:mm:ss')
<Arrow [2018-02-24T12:30:45+00:00]>

遵循ISO-8601的字符串不需要格式字符串参数即可转换

	
>>> arrow.get('2018-02-24T13:00:00.000-07:00')
<Arrow [2018-02-24T13:00:00-07:00]>

可以从字符串中通过格式参数搜索时间

>>> arrow.get('June was born in May 1980', 'MMMM YYYY')
<Arrow [1980-05-01T00:00:00+00:00]>

直接创建arrow对象

>>> arrow.get(2018, 2, 24)
<Arrow [2018-02-24T00:00:00+00:00]>
 
>>> arrow.Arrow(2018, 2, 24)
<Arrow [2018-02-24T00:00:00+00:00]>

arrow对象属性 datetime,timestamp,native,tzinfo

>>> a = arrow.utcnow()
>>> a.datetime
datetime.datetime(2021, 7, 29, 16, 41, 34, 441167, tzinfo=tzlocal()) #2021-07-29 16:41:34.441167+08:00
 
>>> a.timestamp()#或 a.float_timestamp
1519478150
 
>>> a.naive
datetime.datetime(2021, 7, 29, 16, 41, 34, 441167) #2021-07-29 16:41:34.441167
 
>>> a.tzinfo
tzlocal()

获取datetime对象的值

>>> now.year #month,day,hour,minute,second,microsecond
2021
>>> now.week #今年第几周
30
>>> now.weekday() # 星期 需要+1
3

**时间推移 a.shift(kwargs)

shift方法获取某个时间之前或之后的时间,关键字参数为years,months,weeks,days,hours,seconds,microseconds

>>> a.shift(weeks=+3)  #三周后
<Arrow [2018-03-17T21:58:04.309575+08:00]> 
 
>>> a.shift(days=-1)   #一天前 
<Arrow [2018-02-23T21:58:04.309575+08:00]
 
>>> a.shift(weekday=6)  #距离最近a的星期日,weekday从0到6
<Arrow [2018-02-25T21:58:04.309575+08:00]>

**时间替换 a.replace(kwargs)

返回一个被替换后的arrow对象,原对象不变

>>> a
<Arrow [2018-02-24T21:58:04.309575+08:00]>
>>> a.replace(hour=9)
<Arrow [2018-02-24T09:58:04.309575+08:00]>

格式化输出 a.format([format_string])

>>> a.format()
'2018-02-24 21:58:04+08:00'
>>> a.format('YYYY-MM-DD HH:mm:ss ZZ')
'2018-02-24 21:58:04 +08:00'

人性化输出 a.humanize()


>>> present = arrow.utcnow()
>>> past = present.shift(hours=-1)
>>> past.humanize()    #相对于当前时间
'an hour age'
>>> future = present.shift(hours=2)
>>> future.humanize(present)  #相对于参数时间
'in 2 hours'
>>> past.humanize(present, locale='zh')  #locale参数可以指定地区语言
'1天前'

时间范围和区间

a.span(string), a.floor(), a.ceil()
arrow.Arrow.span_range(),arrow.Arrow.range()

>>> a
<Arrow [2018-02-24T21:58:04.309575+08:00]>
>>> a.span('hour')  #a所在的时间区间
(<Arrow [2018-02-24T21:00:00+08:00]>, <Arrow [2018-02-24T21:59:59.999999+08:00]>) 
>>> a.floor('hour')  #a所在区间的开始
<Arrow [2018-02-24T21:00:00+08:00]>
>>> a.ceil('hour')  #a所在区间的结尾
<Arrow [2018-02-24T21:59:59.999999+08:00]


>>> start = datetime.datetime(2018, 2, 24, 12, 30)
>>> end = datetime.datetime(2018, 2, 24, 15, 20)
>>> for r in arrow.Arrow.span_range('hour',start,end):  #获取start,end之间的时间区间
...   print(r)
...
(<Arrow [2018-02-24T12:00:00+00:00]>, <Arrow [2018-02-24T12:59:59.999999+00:00]>)
(<Arrow [2018-02-24T13:00:00+00:00]>, <Arrow [2018-02-24T13:59:59.999999+00:00]>)
(<Arrow [2018-02-24T14:00:00+00:00]>, <Arrow [2018-02-24T14:59:59.999999+00:00]>)
(<Arrow [2018-02-24T15:00:00+00:00]>, <Arrow [2018-02-24T15:59:59.999999+00:00]>)
>>> for r in arrow.Arrow.range('hour',start,end):    #获取间隔单位时间的时间
...   print(r)
...
2018-02-24T12:30:00+00:00
2018-02-24T13:30:00+00:00
2018-02-24T14:30:00+00:00

格式化字符串标记
在这里插入图片描述

pendulum

Python 的 pendulum 库和JavaScript 的Moment.js 库用法很类似
安装

pip install pendulum

代码示例

import pendulum

# 1、获取时间
print(pendulum.now())
# 2019-12-12T15:52:35.837803+08:00

print(pendulum.today())
# 2019-12-12T00:00:00+08:00

print(pendulum.tomorrow())
# 2019-12-13T00:00:00+08:00

print(pendulum.yesterday())
# 2019-12-11T00:00:00+08:00


# 2、转字符串
print(pendulum.now().to_datetime_string())
# 2019-12-12 15:51:22

print(pendulum.now().to_date_string())
# 2019-12-12

print(pendulum.now().to_time_string())
# 22:25:05

print(pendulum.now().format('%Y-%m-%d'))
# 2019-12-12


# 3、类型测试
from datetime import datetime
dt =pendulum.datetime(2015, 2, 5)
print(isinstance(dt, datetime))
True


# 4、解析规范的时间
print(pendulum.from_format('2019-12-12', '%Y-%m-%d'))
# 2019-12-12T00:00:00+00:00

print(pendulum.parse('2019-12-12'))
# 2019-12-12T00:00:00+00:00


# 6、属性
now = pendulum.now()
print(now.year)
print(now.month)
print(now.day)
print(now.hour)
print(now.minute)
print(now.second)
# 2019  12  12  22  22 45


# 7、时间加减
now = pendulum.now()
print(now)
# 2019-12-12T22:27:48.429761+08:00

print(now.add(years=1))
# 2020-12-12T22:27:48.429761+08:00

print(now.subtract(years=1))
# 2018-12-12T22:27:48.429761+08:00

# 时间跨度计算
print(now.diff(now.add(years=1)).in_years())
# 1


# 8、设置语言地区
pendulum.set_locale('zh')

print(pendulum.now().subtract(days=1).diff_for_humans())
# 1天前

print(pendulum.now().subtract(hours=1).diff_for_humans())
# 1小时前

# 9、生成时间序列
period = pendulum.period(pendulum.now(), pendulum.now().add(days=3))

# years, months, weeks, days, hours, minutes and seconds
for dt in period.range('days'):
    print(dt)

"""
2019-12-12T22:39:42.142193+08:00
2019-12-13T22:39:42.142193+08:00
2019-12-14T22:39:42.142193+08:00
2019-12-15T22:39:42.142193+08:00
"""

其他示例
获取本周的周一和周日

now = pendulum.now()
print(now.to_date_string())
# 2021-01-14

print(now.start_of("week").to_date_string())
# 2021-01-11

print(now.end_of("week").to_date_string())
# 2021-01-17
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值