Manipulating date and time is a common scenario in any programming language. Without the help of a handy library, it can become a tedious job requiring sufficient effort. Let's have a look at the
Arrow library, which is heavily inspired by popularly used Python libraries
Requests. Arrow provides a friendly approach for handling date and time manipulation, creation, etc.
From the official documentation:
Arrow is a Python library that offers a sensible, human-friendly approach to creating, manipulating, formatting and converting dates, times, and timestamps. It implements and updates the datetime type, plugging gaps in functionality, and provides an intelligent module API that supports many common creation scenarios.
Getting Started With Arrow
To get started with the
Arrow library, you need to have Python installed on your system. Also make sure you have
pip, Python package manager, installed in your environment.
Now install Arrow using pip.
pip install arrow
You'll learn how to use Arrow in your web application development project for date and time manipulation, creation, etc. So let's start by creating a web application using Python Flask.
Using pip, install Python Flask, if it's not already installed.
pip install Flask
Create a file called
app.py which would be the Python application file. Add the following code to
from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Welcome to Arrow Library" if __name__ == '__main__': app.run()
Save the above changes and run the application using
python app.py, and you should have the application running on http://localhost:5000/.
Local Time to UTC Time & Vice Versa
One of the most common scenarios that you face in a web application development project is fetching the local time, converting the local time to UTC (Coordinated Universal Time) time and then converting UTC time to local time for display in a web application based on time zone.
Arrow in your Python Flask project, you need to import the library in
Once it's imported, you can straight away use the arrow object for date and time manipulation and creation.
Let's create a route and method to fetch the local time. Add a route called
getLocalTime and its corresponding method. Arrow provides a method called
now to get the current local time. Use the
now method to get the local time, and to return the date you need to convert it into ISO format. Here is how the code looks:
@app.route("/getLocalTime") def getLocalTime(): local = arrow.now() return local.isoformat()
Save the above changes and restart the server. Point your browser to http://localhost:5000/getLocalTime and you should be able to view the local time.
Normally, you tend to save the date and time in UTC format in databases and display the local time by converting the UTC time to local time. So let's have a look at how to convert the local time to UTC time for database storage.
Create a route and method called
getCurrentUtcTime. In order to get the current UTC time, arrow provides a method called
utcnow. You can use it to get the current UTC time as shown:
@app.route("/getCurrentUtcTime") def getCurrentUtcTime(): utc = arrow.utcnow() return utc.isoformat()
The above method gets the current UTC time. If you already have a date and time for which you want to get the UTC, arrow provides a
to method for doing this. Using the
to method, you need to provide the time zone to which you need the date and time to be converted. So, here is how you can convert the local time to UTC:
@app.route("/getUtcTime") def getUtcTime(): local = arrow.now() utc = local.to('utc') return utc.isoformat()
When you save the date and time in the database, you save it as a timestamp. To get the UTC timestamp, you need to call the
.timestamp attribute of the object.
You cannot show the UTC timestamp when displaying data to the client side. You need to convert the UTC timestamp to local time. In order to do that, you first need to create the arrow object using the
arrow.get method. Then you can use the
arrow.to method to convert the UTC time to local time. Here is how the code looks:
@app.route("/convertUtcToLocal") def convertUtcToLocal(): local = arrow.now() utcTimeStamp = local.to('utc').timestamp localDateObj = arrow.get(utcTimeStamp).to('local') return localDateObj.isoformat()
Save the above changes and restart the server. Point your browser to http://localhost:5000/convertUtcToLocal and you should be able to view local time retrieved by converting the UTC timestamp to local time.
Manipulating Date & Time
Most of the time, it's required to manipulate the date and time by adding or removing a few hours, minutes, etc. to the datetime object. Arrow provides two methods called
shift for manipulating the datetime object.
Let's say that you have an arrow datetime object. Now you want to replace a few things in the datetime object. You want to alter the minute and second of the datetime.
>>> localDateTime = arrow.now() >>> localDateTime <Arrow [2017-09-29T07:39:29.237652+05:30]>
To replace the minute and second of the
localDateTime, you can use the
replace method provided by the arrow library. Here is how the syntax looks:
>>> localDateTime.replace(minute = 01,second = 01) <Arrow [2017-09-29T07:01:01.237652+05:30]>
If you want to increment the datetime by a certain parameter like day, hour, week, etc., you can use the
shift method. All you need to do is provide the parameter using which you need to shift the datetime. Let's say you need to increment the datetime by one day. The code would be like this:
>>> localDateTime = arrow.now() >>> localDateTime <Arrow [2017-09-29T08:03:57.806785+05:30]> >>> localDateTime.shift(days = +1) <Arrow [2017-09-30T08:03:57.806785+05:30]>
To decrement the datetime by two days, the code would be like:
>>> localDateTime.shift(days = -2) <Arrow [2017-09-27T08:03:57.806785+05:30]>
Formatting the Date Using Arrow
In order to format the datetime as per your custom format, you can use the
format method provided by arrow.
For example, to format datetime to
YYYY-MM-DD format, you need to use the following code:
>>> localDateTime = arrow.now() >>> localDateTime <Arrow [2017-09-29T08:32:28.309863+05:30]> >>> localDateTime.format('YYYY-MM-DD') u'2017-09-29'
Similarly, to format datetime to
YYYY-MM-DD HH:mm:ss format, you need to use the following code:
>>> localDateTime <Arrow [2017-09-29T08:32:28.309863+05:30]> >>> localDateTime.format('YYYY-MM-DD HH:mm:ss') u'2017-09-29 08:32:28'
Human-Friendly DateTime Representation
Arrow provides a method called
humanize to represent the datetime in a human-friendly representation. Most of the time, the user needs to know how much time it has been since a particular time. You can use the
humanize method to show the user how much time it has been since now. Here is some example code:
>>> currentDate = arrow.now() >>> currentDate <Arrow [2017-09-29T22:05:26.940228+05:30]> >>> currentDate.humanize() u'just now'
As seen in the above code, if you use humanize to represent how much time it has been since the current datetime, it would show the above result.
Now let's take a look at a prior date.
>>> earlierDate = arrow.now().shift(days=-3) >>> earlierDate <Arrow [2017-09-26T22:07:39.610546+05:30]> >>> earlierDate.humanize() u'3 days ago'
As seen in the above code, you just used the
humanize method with an earlier date, and it shows the relative number of days with respective to the current date.
You can also use
humanize to show the relative number of days between two dates. For example:
>>> laterDate = arrow.now().shift(days=+3) >>> laterDate <Arrow [2017-10-02T22:10:58.505234+05:30]> >>> earlierDate = arrow.now().shift(days=-3) >>> earlierDate <Arrow [2017-09-26T22:11:11.927570+05:30]> >>> earlierDate.humanize(laterDate) u'5 days ago'
As seen in the above example, you created a later date and an earlier date by shifting the number of days. Then you checked the relative number of days from
laterDate using the
humanize method, which printed the above message.
Converting to a Different Time Zone
Arrow provides a
convert method to convert the local time to a preferred time zone. For example to convert the local time to UTC time, you can use the following command:
>>> arrow.now().to('utc') <Arrow [2017-09-30T16:58:45.630252+00:00]>
To convert the UTC time back to the local time zone, you can use the following code:
>>> utcTime = arrow.now().to('utc') >>> utcTime <Arrow [2017-09-30T17:01:30.673791+00:00]> >>> utcTime.to('local') <Arrow [2017-09-30T22:31:30.673791+05:30]>
To convert the UTC time to any specific time zone, you can specify the time zone and you'll get the time from that particular time zone. For example:
>>> utcTime.to('America/New_York') <Arrow [2017-09-30T13:01:30.673791-04:00]>
In the above code, you specified the UTC time to be converted to the
America/New_York time zone, and similarly you can provide any time zone that you want the UTC to be converted to.
Wrapping It Up
In this tutorial, you saw how to use Arrow, a Python library for date and time manipulation, creation and formatting. From a developer point of view, the Arrow library seems to be a complete fit for date and time manipulations when used in a Python project.
Additionally, don’t hesitate to see what we have available for sale and for study in Envato Market, and don't hesitate to ask any questions and provide your valuable feedback using the feed below.
Do you have any prior experience using the Arrow library? What is your point of view? Did you face any issues while using the library? Do let us know your thoughts and suggestions in the comments below.