# pendulum使用整理

pendulum使的操作时间变得更简单. 下面参照官网列举一些常见的操作,整的很简单的哦!

## 安装

``````

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)

``````
``````

5.4青年节: 2017-05-04T00:00:00+08:00

``````

## 日期计算

``````

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)

``````
``````

day: 2017-05-20T17:00:39.052688+08:00
day: 2017-05-21T17:00:39.052688+08:00
day: 2017-05-22T17:00:39.052688+08:00
day: 2017-05-23T17:00:39.052688+08:00
day: 2017-05-24T17:00:39.052688+08:00
day: 2017-05-25T17:00:39.052688+08:00
day: 2017-05-26T17:00:39.052688+08:00
day: 2017-05-27T17:00:39.052688+08:00

``````

## 日期转换

``````

In [25]:

import pendulum
pendulum.parse('2017-5-1')

``````
``````

Out[25]:

<Pendulum [2017-05-01T00:00:00+00:00]>

``````
``````

In [26]:

pendulum.parse('20160413')

``````
``````

Out[26]:

<Pendulum [2016-04-13T00:00:00+00:00]>

``````
``````

In [27]:

pendulum.parse('2016-W07-5')

``````
``````

Out[27]:

<Pendulum [2016-02-19T00:00:00+00:00]>

``````

## 时间间隔

``````

In [36]:

# Interval

it = pendulum.interval(days=15)
print(it.weeks,it.days,it.hours)
print(it.in_hours()) # 以小时表示间隔

``````
``````

2 15 0
360

``````
``````

In [52]:

# Period 是 Interval的 特例

dt1 = pendulum.now()
# 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)

``````
``````

2017-05-27T18:28:37.427593+08:00
2017-05-28T18:28:37.427593+08:00
2017-05-29T18:28:37.427593+08:00
2017-05-30T18:28:37.427593+08:00

``````

## 时间戳

``````

In [4]:

import pendulum
print(pendulum.from_timestamp(1477548306).to_datetime_string())
print(pendulum.from_timestamp(1477548306, 'Asia/Shanghai').to_datetime_string())

``````
``````

2016-10-27 06:05:06
2016-10-27 14:05:06

``````