Python与日期、时间相关的内置模块:time、datetime、calendar,以及第三方模块:moment(使用体验更好)

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-31 22:56:54

Python 与日期、时间相关的内置模块,主要有:timedatetimecalendar 等,一般常见的问题,使用它们就足够了,但遇到复杂度很高的需求时,代码的可读性就会变得很差,所以,我们还可以使用体验更好的第三方模块:moment 。本文会从内置模块介绍到第三方模块。

time

time 是用来表示时分秒。

获取时间

import time
print(time.time())

1559201353.5570097

得到的是一个 时间戳,是从 1970-01-01 00:00:00 (时间基准点)到现在的秒数,数据类型是浮点型,是 UTC 时间。

UTC 的由来,全球分为24个时区,每个时区都自己的本地时间,为了能有一个统一的时间,所以设置了 UTC(Universal Time Coordinated,通用协调时),都与英国伦敦的本地时间一样。

但时间戳对于人来讲,可读性极差,所以我们需要将其转换成日常使用的形式。

转换时间戳

import time

# 输出 UTC 时间的年月日时分秒结构体
print('UTC:', time.gmtime(time.time())

# 输出本地时间的年月日时分秒结构体
print('localtime:', time.localtime(time.time())

UTC: time.struct_time(tm_year=2019, tm_mon=5, tm_mday=30, tm_hour=7, tm_min=29, tm_sec=13, tm_wday=3, tm_yday=150, tm_isdst=0)

localtime: time.struct_time(tm_year=2019, tm_mon=5, tm_mday=30, tm_hour=15, tm_min=29, tm_sec=13, tm_wday=3, tm_yday=150, tm_isdst=0)

仔细观察的话,会发现我们的本地时间与 UTC 相差了 8 小时,这正是北京和伦敦的时差。

虽然现在也可以看出具体的日期,但还不是很方便,我们可以进一步格式化 struct_time ,得到更直观的日期字符串。

import time

st = time.localtime(time.time())
tf = time.strftime('%Y-%m-%d %H:%M:%S', st)
print(tf)

2019-05-30 15:29:13

# 我们还可以将日期字符串转换成 struct_time
st = time.strptime(tf, '%Y-%m-%d %H:%M:%S')
print(st)

time.struct_time(tm_year=2019, tm_mon=5, tm_mday=30, tm_hour=15, tm_min=29, tm_sec=13, tm_wday=3, tm_yday=150, tm_isdst=0)

strftimestrptime 是一对通过日期格式模板进行相互转换的方法。

如果你嫌上面还是麻烦的话,只想快速看到日期,也是可以的。

import time

# ctime 内部是先将时间戳转换成 struc_time,再调用 time.asctime 转换成字符串。
print(time.ctime(time.time())

Thu May 30 15:29:13 2019

datetime

datetime 是用来表示日期的,即年月日时分秒。其与 time 相比更侧重于日期方面的处理,比如:日期的加减、比较等。

创建日期

import datetime
import time

# 通过时间戳创建日期,此为当前日期
dt = datetime.datetime.fromtimestamp(time.time())

# 这两种方法是相同的效果,都是简化创建当前日期
now = datetime.datetime.now()
today = datetime.datetime.today()

需要注意的是,datetime 默认创建的是本地时间的日期,这与 time 是不同的。如果想创建 UTC 日期,则可以通过 datetimeutcfromtimestamputcnow 方法。

datetime 也提供了通过字符串创建日期的方式,也是为简化操作,方便使用。

import datetime

dt = datetime.datetime.strptime('2019-05-30 15:29:13
', '%Y-%m-%d %H:%M:%S')

日期加减

import datetime

dt_0 = datetime.datetime.now()
dt_1 = datetime.timedelta(seconds=10)

dt_2 = dt_0 - dt_1
dt_3 = dt_0 + dt_1

print('-:', dt_2)
print('+:', dt_3)

-: 2019-05-30 16:45:13.642651
+: 2019-05-30 16:45:33.642651

datetime.timedelta 作为时间的间隔对象。

calendar

calendar 是用来表示年月日,同时也包含了星期的信息。

import calendar

# 显示日历
cal = calendar.month(2019, 7)
print(cal)

     July 2019
Mo Tu We Th Fr Sa Su
 1  2  3  4  5  6  7
 8  9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31

# 查询星期
weekday = calendar.weekday(2019, 7, 1)
print(weekday)

# 0 表示为星期一
0

calendar 使用起来就像查日历一样,解决日历方面的需求。

moment

moment,是为了解决 Python 在处理日期时那种蹩脚的语法,提供更易用的方式。灵感来自于 javascript 的 Moment.js

通过 pip install moment 进行安装。

使用教程如下:

import moment
from datetime import datetime

# Create a moment from a string
moment.date("12-18-2012")

# Create a moment with a specified strftime format
moment.date("12-18-2012", "%m-%d-%Y")

# Moment uses the awesome dateparser library behind the scenes
moment.date("2012-12-18")

# Create a moment with words in it
moment.date("December 18, 2012")

# Create a moment that would normally be pretty hard to do
moment.date("2 weeks ago")

# Create a future moment that would otherwise be really difficult
moment.date("2 weeks from now")

# Create a moment from the current datetime
moment.now()

# The moment can also be UTC-based
moment.utcnow()

# Create a moment with the UTC time zone
moment.utc("2012-12-18")

# Create a moment from a Unix timestamp
moment.unix(1355875153626)

# Create a moment from a Unix UTC timestamp
moment.unix(1355875153626, utc=True)

# Return a datetime instance
moment.date(2012, 12, 18).date

# We can do the same thing with the UTC method
moment.utc(2012, 12, 18).date

# Create and format a moment using Moment.js semantics
moment.now().format("YYYY-M-D")

# Create and format a moment with strftime semantics
moment.date(2012, 12, 18).strftime("%Y-%m-%d")

# Update your moment's time zone
moment.date(datetime(2012, 12, 18)).locale("US/Central").date

# Alter the moment's UTC time zone to a different time zone
moment.utcnow().timezone("US/Eastern").date

# Set and update your moment's time zone. For instance, I'm on the
# west coast, but want NYC's current time.
moment.now().locale("US/Pacific").timezone("US/Eastern")

# In order to manipulate time zones, a locale must always be set or
# you must be using UTC.
moment.utcnow().timezone("US/Eastern").date

# You can also clone a moment, so the original stays unaltered
now = moment.utcnow().timezone("US/Pacific")
future = now.clone().add(weeks=2)

# Customize your moment by chaining commands
moment.date(2012, 12, 18).add(days=2).subtract(weeks=3).date

# Imagine trying to do this with datetime, right?
moment.utcnow().add(years=3, months=2).format("YYYY-M-D h:m A")

# You can use multiple keyword arguments
moment.date(2012, 12, 19).add(hours=1, minutes=2, seconds=3)

# And, a similar subtract example...
moment.date(2012, 12, 19, 1, 2, 3).subtract(hours=1, minutes=2, seconds=3)

# In addition to adding/subtracting, we can also replace values
moment.now().replace(hours=5, minutes=15, seconds=0).epoch()

# And, if you'd prefer to keep the microseconds on your epoch value
moment.now().replace(hours=5, minutes=15, seconds=0).epoch(rounding=False)

# Years, months, and days can also be set
moment.now().replace(years=1984, months=1, days=1, hours=0, minutes=0, seconds=0)

# Also, datetime properties are available
moment.utc(2012, 12, 19).year == 2012

# Including plural ones (since I'm bad at remembering)
moment.now().seconds

# We can also manipulate to preferred weekdays, such as Monday
moment.date(2012, 12, 19).replace(weekday=1).strftime("%Y-%m-%d")

# Or, this upcoming Sunday
moment.date("2012-12-19").replace(weekday=7).date

# We can even go back to two Sundays ago
moment.date(2012, 12, 19).replace(weekday=-7).format("YYYY-MM-DD")

# It's also available as a property
moment.utcnow().weekday

# And, there's an easy way to zero out the hours, minutes, and seconds
moment.utcnow().zero

最后,安利大家一本书《深入理解NLP的中文分词:从原理到实践》,让你从零掌握中文分词技术,踏入NLP的大门。

如果因为以上内容对你有所帮助,希望你能帮个忙,点个赞、评个论、转个发,关个注。

此公众号每周分享一篇干货文章,实实在在把一个课题说明白,讲清楚,望关注!
惠惠周刊

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!