SoFunction
Updated on 2024-11-16

Python uses arrow library to elegantly handle time data in detail

preamble

We all know that there are many times when we have to deal with time, but the module for dealing with time in the Python standard library is not really designed to be very user-friendly, why do I say that? Because I believe that most people almost every time when dealing with time data again and again to check the documentation, such as time and text format conversion, time increase and decrease and other seemingly very basic operations, in Python to deal with it is not simple.

The worst part is that there are two modules in the Python standard library that deal with time, one called time and the other called datetime, which provide similar methods but are not the same thing at all. And that's not all. There's also a module called calendar in the standard library, which also handles time.

Today I'm not taking you through all three of them because just because you remember now doesn't mean you won't forget later. Today features a time processing library so elegant that I couldn't pass it up - arrow.

synopsis

arrow is a lightweight Python library specializing in time and dates that provides a sensible, intelligent way to create, manipulate, format, and convert time and dates.

mounting

pip install arrow

utilization

Let's look directly at the code, commenting both the dividing line.

>>> import arrow

# Get the current time
>>> utc = ()
>>> utc
<Arrow [2017-05-11T21:23:58.970460+00:00]>

# Adjustment time
>>> utc = (days=+1, hours=-1)
>>> utc
<Arrow [2017-05-12T20:23:58.970460+00:00]>

# Revision time
>>> (hour=4, minute=40)
<Arrow [2017-05-12T04:40:58.970460+00:00]>

# Switching time zones
>>> local = ('US/Pacific')
>>> local
<Arrow [2017-05-11T13:23:58.970460-07:00]>

# From text to time objects
>>> ('2017-05-11T21:23:58.970460+00:00')
<Arrow [2017-05-11T21:23:58.970460+00:00]>

>>> (1367900664)
<Arrow [2017-05-07T04:24:24+00:00]>

>>> ('June was born in May 1980', 'MMMM YYYY')
<Arrow [1980-05-01T00:00:00+00:00]>

# Get timestamp
>>> 
1368303838

# Formatted output
>>> ()
'2017-05-11 13:23:58 -07:00'

>>> ('YYYY-MM-DD HH:mm:ss')
'2017-05-11 13:23:58'

>>> ()
'an hour ago'

# Converted to standard library objects
>>> ()
(2017, 5, 7)

>>> ()
(4, 38, 15, 447644)

summarize

I'm not lying to you, am I? If your Python project needs to deal with time in the future, ditch the standard library decisively, arrow will save you countless brain cells.

Well, the above is the full content of this article, I hope that the content of this article on your learning or work has a certain reference learning value, if there are questions you can leave a message to exchange, thank you for my support.

Attached is the official documentation for arrow, for more cool uses go to the official website.

/en/latest/