实用又强大,6款Python时间&日期库推荐

在使用 Python 的开发过程中,除了使用 datetime 标准库来处理时间和日期,还有许多第三方的开源库值得尝试。

1、Arrow

Arrow 是一个专门处理时间和日期的轻量级 Python 库,它提供了一种合理、智能的方式来创建、操作、格式化、转换时间和日期,并提供了一个支持许多常见构建方案的智能模块 API 。简单来说,它可以帮你以更简便的操作和更少的代码来使用日期和时间。其设计灵感主要来源于 moment.js 和 requests 。

Quick start

  1. $ pip install arrow
  1. >>> import arrow
  2. >>> utc = arrow.utcnow()
  3. >>> utc
  4. <Arrow [2013-05-11T21:23:58.970460+00:00]>
  5.  
  6. >>> utc = utc.replace(hours=-1)
  7. >>> utc
  8. <Arrow [2013-05-11T20:23:58.970460+00:00]>
  9.  
  10. >>> local = utc.to(‘US/Pacific’)
  11. >>> local
  12. <Arrow [2013-05-11T13:23:58.970460-07:00]>
  13.  
  14. >>> arrow.get(‘2013-05-11T21:23:58.970460+00:00’)
  15. <Arrow [2013-05-11T21:23:58.970460+00:00]>
  16.  
  17. >>> local.timestamp
  18. 1368303838
  19.  
  20. >>> local.format()
  21. ‘2013-05-11 13:23:58 -07:00’
  22.  
  23. >>> local.format(‘YYYY-MM-DD HH:mm:ss ZZ’)
  24. ‘2013-05-11 13:23:58 -07:00’
  25.  
  26. >>> local.humanize()
  27. ‘an hour ago’
  28.  
  29. >>> local.humanize(locale=‘ko_kr’)
  30. ‘1시간 전’

2、Delorean

Delorean 提供了一个相比于 datetime 和 pytz 的更好的抽象,让你处理时间更容易。它有很多有用的处理时区的特性,标准化时区或者从一个时区改变到另外一个时区。

Quick start

  1. from datetime import datetime
  2. import pytz
  3.  
  4. est = pytz.timezone(‘US/Eastern’)
  5. d = datetime.now(pytz.utc)
  6. d = est.normalize(d.astimezone(est))
  7. return d
  1. from delorean import Delorean
  2.  
  3. d = Delorean()
  4. d = d.shift(‘US/Eastern’)
  5. return d

3、Pendulum

原生的 datetime 足够应付基本情况,但当面对更复杂的用例时,通常会有的捉襟见肘,不那么直观。 Pendulum 在标准库的基础之上,提供了一个更简洁,更易于使用的 API ,旨在让 Python datetime 更好用。

Quick start

  1. >>> import pendulum
  2.  
  3. >>> now_in_paris = pendulum.now(‘Europe/Paris’)
  4. >>> now_in_paris
  5. ‘2016-07-04T00:49:58.502116+02:00’
  6.  
  7. # Seamless timezone switching
  8. >>> now_in_paris.in_timezone(‘UTC’)
  9. ‘2016-07-03T22:49:58.502116+00:00’
  10.  
  11. >>> tomorrow = pendulum.now().add(days=1)
  12. >>> last_week = pendulum.now().subtract(weeks=1)
  13.  
  14. >>> if pendulum.now().is_weekend():
  15. …     print(‘Party!’)
  16. ‘Party!’
  17.  
  18. >>> past = pendulum.now().subtract(minutes=2)
  19. >>> past.diff_for_humans()
  20. >>> ‘2 minutes ago’
  21.  
  22. >>> delta = past – last_week
  23. >>> delta.hours
  24. 23
  25. >>> delta.in_words(locale=‘en’)
  26. ‘6 days 23 hours 58 minutes’
  27.  
  28. # Proper handling of datetime normalization
  29. >>> pendulum.create(2013, 3, 31, 2, 30, 0, 0, ‘Europe/Paris’)
  30. ‘2013-03-31T03:30:00+02:00’ # 2:30 does not exist (Skipped time)
  31.  
  32. # Proper handling of dst transitions
  33. >>> just_before = pendulum.create(2013, 3, 31, 1, 59, 59, 999999, ‘Europe/Paris’)
  34. ‘2013-03-31T01:59:59.999999+01:00’
  35. >>> just_before.add(microseconds=1)
  36. ‘2013-03-31T03:00:00+02:00’

4、dateutil

dateutil 是 datetime 标准库的一个扩展库,几乎支持以所有字符串格式对日期进行通用解析,日期计算灵活,内部数据更新及时。

Quick start

  1. >>> from dateutil.relativedelta import *
  2. >>> from dateutil.easter import *
  3. >>> from dateutil.rrule import *
  4. >>> from dateutil.parser import *
  5. >>> from datetime import *
  6. >>> now = parse(“Sat Oct 11 17:13:46 UTC 2003”)
  7. >>> today = now.date()
  8. >>> year = rrule(YEARLY,dtstart=now,bymonth=8,bymonthday=13,byweekday=FR)[0].year
  9. >>> rdelta = relativedelta(easter(year), today)
  10. >>> print(“Today is: %s” % today)
  11. Today is: 2003-10-11
  12. >>> print(“Year with next Aug 13th on a Friday is: %s” % year)
  13. Year with next Aug 13th on a Friday is: 2004
  14. >>> print(“How far is the Easter of that year: %s” % rdelta)
  15. How far is the Easter of that year: relativedelta(months=+6)
  16. >>> print(“And the Easter of that year is: %s” % (today+rdelta))
  17. And the Easter of that year is: 2004-04-11

5、moment

用于处理日期/时间的 Python 库,设计灵感同样是来源于 moment.js 和 requests ,设计理念源自 Times Python 模块。

Usage

  1. import moment
  2. from datetime import datetime
  3.  
  4. Create a moment from a string
  5. moment.date(“12-18-2012”)
  6.  
  7. Create a moment with a specified strftime format
  8. moment.date(“12-18-2012”“%m-%d-%Y”)
  9.  
  10. # Moment uses the awesome dateparser library behind the scenes
  11. moment.date(“2012-12-18”)
  12.  
  13. Create a moment with words in it
  14. moment.date(“December 18, 2012”)
  15.  
  16. Create a moment that would normally be pretty hard to do
  17. moment.date(“2 weeks ago”)
  18.  
  19. Create a future moment that would otherwise be really difficult
  20. moment.date(“2 weeks from now”)
  21.  
  22. Create a moment from the current datetime
  23. moment.now()
  24.  
  25. # The moment can also be UTC-based
  26. moment.utcnow()
  27.  
  28. Create a moment with the UTC time zone
  29. moment.utc(“2012-12-18”)
  30.  
  31. Create a moment from a Unix timestamp
  32. moment.unix(1355875153626)
  33.  
  34. Create a moment from a Unix UTC timestamp
  35. moment.unix(1355875153626, utc=True)
  36.  
  37. Return a datetime instance
  38. moment.date(2012, 12, 18).date
  39.  
  40. # We can do the same thing with the UTC method
  41. moment.utc(2012, 12, 18).date
  42.  
  43. Create and format a moment using Moment.js semantics
  44. moment.now().format(“YYYY-M-D”)
  45.  
  46. Create and format a moment with strftime semantics
  47. moment.date(2012, 12, 18).strftime(“%Y-%m-%d”)
  48.  
  49. Update your moment’s time zone
  50. moment.date(datetime(2012, 12, 18)).locale(“US/Central”).date
  51.  
  52. Alter the moment’s UTC time zone to a different time zone
  53. moment.utcnow().timezone(“US/Eastern”).date
  54.  
  55. Set and update your moment‘s time zone. For instance, I’on the
  56. # west coast, but want NYC’s current time.
  57. moment.now().locale(“US/Pacific”).timezone(“US/Eastern”)
  58.  
  59. In order to manipulate time zones, a locale must always be set or
  60. # you must be using UTC.
  61. moment.utcnow().timezone(“US/Eastern”).date
  62.  
  63. # You can also clone a moment, so the original stays unaltered
  64. now = moment.utcnow().timezone(“US/Pacific”)
  65. future = now.clone().add(weeks=2)

6、When.py

提供对用户非常友好的特性来帮助执行常见的日期和时间操作。

Usage