pendulum使的操作时间变得更简单. 下面参照官网列举一些常见的操作,整的很简单的哦!
官网也介绍了pendulum
在sqlite3
、mysqlclient
、django
使用需要的设置,日常开发绝对够了
In [1]:
!pip install pendulum
In [11]:
# 当前时间的获取
import pendulum
now = pendulum.now()# 当前时间
print("当前时间:",now)
now_in_paris = pendulum.now('Europe/Paris')
print("巴黎时间:",now_in_paris)
print("当前时间转UTC时间:", now.in_timezone('UTC'))
In [22]:
now = pendulum.create(2017, 5, 4, 0, 0, 0, 0, 'Asia/Shanghai')
print("5.4青年节:", now)
In [30]:
import pendulum
now = pendulum.now() # 今天
tomorrow = now.add(days = 1) # 明天
last_week = now.subtract(weeks=1) # 上周
print("今天:",now)
print("明天:",tomorrow)
print("上周:",last_week)
if now.is_weekend():
print("哇,周末了!")
delta = now - last_week
print("今天距离上周:", delta.days, "天")
print("上周到今天每一天:")
for day in delta:
print("day:", day)
支持各种格式. 包括
星期日历表示法
,可以查看一下ISO_8601
In [25]:
import pendulum
pendulum.parse('2017-5-1')
Out[25]:
In [26]:
pendulum.parse('20160413')
Out[26]:
In [27]:
pendulum.parse('2016-W07-5')
Out[27]:
In [36]:
# Interval
it = pendulum.interval(days=15)
print(it.weeks,it.days,it.hours)
print(it.in_hours()) # 以小时表示间隔
In [52]:
# Period 是 Interval的 特例
dt1 = pendulum.now()
dt2 = dt1.add(days=3)
# A period is the difference between 2 instances
period = dt2 - dt1
print("日期相差:",period.in_hours(),"小时")
print("日期相差(日期之间包含的工作日):",period.in_weekdays(),"天")
print("日期相差(日期之间包含的周末):",period.in_weekend_days(),"天")
# A period is iterable
for dt in period:
print(dt)
In [4]:
import pendulum
print(pendulum.from_timestamp(1477548306).to_datetime_string())
print(pendulum.from_timestamp(1477548306, 'Asia/Shanghai').to_datetime_string())