Although Python provides multiple built-in modules for manipulating date and time, sometimes they cannot meet our needs, so the following article mainly introduces how Python uses the arrow library to handle time data elegantly. Friends who need it can refer to relevant information. Let’s take a look below.
Preface
#Everyone should know that we have to deal with time many times, but when dealing with time in the Python standard library The module is actually not very user-friendly. Why do I say that? Because I believe that most people look up documents again and again almost every time when processing time data. For example, seemingly very basic operations such as time and text format conversion, time increase and decrease, etc., can be processed in Python. Not simple.
The most terrible thing is that there are actually two modules in the Python standard library that handle time, one is called time and the other is called datetime. They provide similar methods, but the two are completely different. It’s not over yet. There is also a module called calendar in the standard library, which is also used to handle time.
Today I won’t take you to understand the relationship between the three of them, because just because you remember it now doesn’t mean you won’t forget it in the future. Today's hero is a time processing library that is so elegant that I can't pass it up - arrow.
Introduction
arrow is a lightweight Python library that specializes in processing time and date. It provides a reasonable, The smart way to create, manipulate, format, and convert times and dates.
Installation
##
pip install arrow
Use
>>> import arrow # 获取当前时间 >>> utc = arrow.utcnow() >>> utc <Arrow [2017-05-11T21:23:58.970460+00:00]> # 调整时间 >>> utc = utc.shift(days=+1, hours=-1) >>> utc <Arrow [2017-05-12T20:23:58.970460+00:00]> # 修改时间 >>> utc.replace(hour=4, minute=40) <Arrow [2017-05-12T04:40:58.970460+00:00]> # 转换时区 >>> local = utc.to('US/Pacific') >>> local <Arrow [2017-05-11T13:23:58.970460-07:00]> # 从文本转为时间对象 >>> arrow.get('2017-05-11T21:23:58.970460+00:00') <Arrow [2017-05-11T21:23:58.970460+00:00]> >>> arrow.get(1367900664) <Arrow [2017-05-07T04:24:24+00:00]> >>> arrow.get('June was born in May 1980', 'MMMM YYYY') <Arrow [1980-05-01T00:00:00+00:00]> # 获取时间戳 >>> local.timestamp 1368303838 # 格式化输出 >>> local.format() '2017-05-11 13:23:58 -07:00' >>> local.format('YYYY-MM-DD HH:mm:ss') '2017-05-11 13:23:58' >>> local.humanize() 'an hour ago' # 转为标准库对象 >>> a.date() datetime.date(2017, 5, 7) >>> a.time() datetime.time(4, 38, 15, 447644)
Summary
I didn’t lie to you, did I? If your Python project requires processing time in the future, please decisively abandon the standard library, arrow will save you countless brain cells.The above is the detailed content of Detailed example of using arrow library to process time data in Python. For more information, please follow other related articles on the PHP Chinese website!