Great! The most comprehensive Python processing date and time comprehensive summary!

Posted by mr_zhang on Tue, 09 Nov 2021 04:30:58 +0100

Author Qian Wei Way


Python's time processing module is used more and more in daily use, but it is basically to check the data, which is still troublesome. Sort it out for convenient use in the future


  • Time related concepts
  • Python time module
    • Time formatting
    • t PI DAR
    • Other built-in functions of time module
    • Properties contained in the time module
  • datetime module
    • date class
    • time class
    • datetime class
    • timedelta class
    • tzinfo class
  • pytz module
    • Time zone conversion
    • Daylight saving time processing
  • dateutil module
    • parser.parse()
    • rrule.rrule()
  • Arrow
    • UTC time
    • local time
    • Resolution time
    • Unix timestamp
    • Format date and time
    • Convert to area time
    • weekdays
    • Moving time
    • Daylight saving time
    • Humanized date and time
  • ISO 8601 class

Time related concepts

Second at the 13th International Conference on weights and measures in 1967, it was decided to take the second defined by atomic time as the international standard unit of time: the duration of 9192631770 cycles corresponding to the transition between two hyperfine energy levels of the ground state of cesium 133 atom, and the starting epoch was set at 0:00 on January 1, 1958.

Atomic clock is a kind of clock, which calculates and maintains the accuracy of time according to the standard of atomic resonance frequency. Atomic clock is the most accurate time measurement and frequency standard in the world.

GMT Greenwich Mean Time refers to the standard time of the Royal Greenwich Observatory in the suburbs of London, because the Prime meridian is defined as the longitude passing through there. GMT is also called universal time UT.

UTC Coordinated Universal Time, also known as world standard time, is based on the international atomic clock with an error of nanoseconds per day. The second length of Coordinated Universal Time is consistent with that of atomic time, and the time is required to be close to universal time as much as possible (the difference between the two is required to be kept within 0.9 seconds).

Leap seconds are not only leap years, but also leap seconds. Leap second refers to the adjustment of increasing or decreasing coordinated universal time by 1 second at the end of the year or in the middle of the year (or at the end of the quarter) as uniformly stipulated by the International Bureau of Metrology in order to keep coordinated universal time close to universal time. Due to the non-uniformity of the earth's rotation and long-term chronicity (mainly caused by tidal friction), when the difference between world time (civil time) and atomic time exceeds ± 0.9 seconds, set the world time forward by 1 second (negative leap second, the last minute is 59 seconds) or backward by 1 second (positive leap second, the last minute is 61 seconds); Leap seconds are usually added at the end of the Gregorian calendar or at the end of June.

Time zones are areas on the earth that are defined using the same time. The relevant international conference decided to divide the earth's surface into 24 time zones from south to North according to the longitude, and stipulated that the time difference between adjacent areas was one hour. When people cross an area, they will correct their clock for 1 hour (minus 1 hour to the West and plus 1 hour to the East), and increase or decrease a few hours when they cross several areas. For example, Greater China is located in the East eighth District, which is expressed as GMT+8.

Daylight Saving Time (DST), also known as Daylight Saving Time, Daylight Saving Time or Daylight Saving Time. This is a system of artificially setting local time in order to save energy. In summer, the daytime will be longer, so in order to save electricity, some areas will set their time one hour earlier in summer, that is, the original time zone was 8 o'clock, but the sun appeared earlier in summer, so move the time forward, At 8 o'clock, it was set as 9 o'clock of the day (one hour earlier). In this way, we can use sunshine lighting and save the time of power consumption. Therefore, it will be called time saving in summer!

Unix timestamp refers to the total number of seconds since 0:0:0 on January 1, 1970, coordinated universal time (UTC), regardless of leap seconds.

Python time module

In Python documents, time is classified in Generic Operating System Services. In other words, the functions it provides are closer to the operating system level. Reading through the document, we can see that the time module is carried out around Unix Timestamp.

The module mainly includes a class struct_time, several other functions and related constants. It should be noted that most functions in this module call the functions with the same name in the C library of the platform. Therefore, it should be noted that some functions are platform related and may have different effects on different platforms. Another point is that because it is based on Unix Timestamp, the date range it can express is limited to 1970 – 2038. If your code needs to deal with dates outside the above range, you may need to consider using the datetime module.

Get current time and conversion time format

  • time() returns the time in timestamp format (offset in seconds relative to 1.1 00:00:00)
  • ctime() returns the time in string form. You can pass in the time stamp format for conversion
  • Astime () returns the time in the form of string, which can be passed into struct_time is the form of time, which is used for conversion
  • localtime() returns the struct of the current time_ Time format, which can be passed in timestamp format for conversion
  • gmtime() returns the struct of the current time_ Time form, UTC time zone (0 time zone), can be passed in timestamp format time for conversion
>>> import time
>>> time.time()
>>> time.ctime()
'Fri Sep 09 10:00:25 2016'
>>> time.ctime(time.time())
'Fri Sep 09 10:28:08 2016'
>>> time.asctime()
'Fri Sep 09 10:22:40 2016'
>>> time.asctime(time.localtime())
'Fri Sep 09 10:33:00 2016'
>>> time.localtime()
time.struct_time(tm_year=2016, tm_mon=9, tm_mday=9, tm_hour=10, tm_min=1, tm_sec=19, tm_wday=4, tm_yday=253, tm_isdst=0)
>>> time.localtime(time.time())
time.struct_time(tm_year=2016, tm_mon=9, tm_mday=9, tm_hour=10, tm_min=19, tm_sec=11, tm_wday=4, tm_yday=253, tm_isdst=0)
>>> time.gmtime()
time.struct_time(tm_year=2016, tm_mon=9, tm_mday=9, tm_hour=2, tm_min=13, tm_sec=10, tm_wday=4, tm_yday=253, tm_isdst=0)
>>> time.gmtime(time.time())
time.struct_time(tm_year=2016, tm_mon=9, tm_mday=9, tm_hour=2, tm_min=15, tm_sec=35, tm_wday=4, tm_yday=253, tm_isdst=0)

struct_time has 9 elements in total, of which the first 6 are year, month, day, hour, minute and second, and the last three respectively represent:

  • tm_wday the day of the week (Sunday is 0)
  • tm_ What day of the year is yday
  • tm_ Is isdst daylight saving time

Time formatting


Put one in struct_ Convert time format to timestamp

>>> time.mktime(time.localtime())

time.strftime(format[,t]) puts a struct_time time is converted to a formatted time string. If t is not specified, time.localtime() is passed in. If any element in the tuple is out of bounds, the error of ValueError will be thrown.

  • %c local corresponding date and time representation
  • %x local corresponding date
  • %X local corresponding time
  • %y remove the year of the century (00 – 99)
  • %Y full year
  • %m month (01 – 12)
  • %b local simplified month name
  • %B local full month name
  • %d the day of the month (01 – 31)
  • %j day of the year (001 – 366)
  • %U number of weeks in a year. (00 – 53 Sunday is the beginning of a week.) all days before the first Sunday are placed in week 0.
  • %W and% U are basically the same, except that% w starts on Monday.
  • %w the day of the week (0 – 6, 0 is Sunday)
  • %a local simplified week name
  • %A local full week name
  • %H the hour of the day (24-hour system, 00 – 23)
  • %I what hour (12 hour system, 01 – 12)
  • %p the corresponding character of local am or pm, "% p" is effective only when used with "% I".
  • %M minutes (00 – 59)
  • %S seconds (01 – 61). The document emphasizes that it is really 0 – 61, not 59. Leap year seconds account for two seconds
  • %The name of the Z time zone (if no empty character exists)
  • %%'%' character
>>> time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
'2016-09-09 10:54:21'


Convert a formatted time string to struct_time. In fact, it and strftime() are inverse operations.

>>> time.strptime(time.ctime())
time.struct_time(tm_year=2016, tm_mon=9, tm_mday=9, tm_hour=11, tm_min=0, tm_sec=4, tm_wday=4, tm_yday=253, tm_isdst=-1)



The thread delays running for the specified time. The unit is seconds.


It should be noted that this has different meanings on different systems. On UNIX systems, it returns the "process time", which is a floating-point number (timestamp) in seconds. In WINDOWS, the first call returns the actual running time of the process. The second call is the running time from the first call to the present. (in fact, it is based on QueryPerformanceCounter() on WIN32, which is more accurate than the representation of milliseconds)

import time
print("clock1:%s" % time.clock())
print("clock2:%s" % time.clock())
print("clock3:%s" % time.clock())

The operation result is:


The first clock() outputs the program running time, and the second and third clock() outputs the time interval with the first clock

Other built-in functions of time module

  • altzone() returns the number of seconds offset from the daylight saving time region west of Greenwich. If the region is east of Greenwich, it will return a negative value (such as Western Europe, including the UK). Only the region enabled for daylight saving time can be used.
  • tzset() reinitializes the time related settings according to the environment variable TZ.

Properties contained in the time module

  • timezone is the number of seconds offset from Greenwich in the local time zone (daylight saving time is not activated) (> 0, America; < = 0, most of Europe, Asia and Africa).
  • tzname contains a pair of strings that vary according to the situation. They are the local time zone name with daylight saving time and the local time zone name without daylight saving time.
import time

Operation results

('\xd6\xd0\xb9\xfa\xb1\xea\xd7\xbc\xca\xb1\xbc\xe4', '\xd6\xd0\xb9\xfa\xcf\xc4\xc1\xee\xca\xb1')
China standard time
 China Daylight Time 

datetime module

Datetime is much more advanced than time. It can be understood that datetime is encapsulated based on time and provides more practical functions.

The datetime module defines the following classes:

  • Date: a class representing a date. Common attributes are year, month and day
  • Time: a class representing time. The commonly used attributes are hour, minute, second and microsecond
  • datetime: indicates the date time
  • timedelta: represents the time interval, that is, the length between two time points
  • tzinfo: relevant information related to time zone

Note: the above types of objects are immutable.

date class

The date class defines some common class methods and class attributes:

  • max, min: the maximum and minimum date that the date object can represent
  • resolution: the date object represents the smallest unit of the date. This is heaven
  • today(): returns a date object representing the current local date
  • From time stamp (timestamp): returns a date object according to a given time stamp
  • From ordinal: convert Gregorian calendar time to date object (not used for special calendars)
from datetime import date
import time
print('date.max:', date.max)
print('date.min:', date.min)
print('date.resolution:', date.resolution)
print('date.fromtimestamp():', date.fromtimestamp(time.time()))

Execution results:

date.max: 9999-12-31
date.min: 0001-01-01
date.resolution: 1 day, 0:00:00 2016-09-12
date.fromtimestamp(): 2016-09-12

Instance methods and properties provided by date:

  • . year: return year
  • . month: returns the month
  • . day: return day
  • . replace(year, month, day): generate a new date object, and replace the attributes in the original object with the year, month and day specified by the parameter. (the original object remains unchanged)
  • . weekday(): return weekday. If it is Monday, return 0; If it is Tuesday, return 1, and so on
  • . isoweekday(): returns weekday, or 1 if it is Monday; If it is Tuesday, return 2, and so on
  • . isocalendar(): return format, such as (year, wk num, wk day)
  • . isoformat(): returns a string in the format of 'YYYY-MM-DD'
  • . strftime(fmt): custom format string. Similar to strftime in the time module.
  • . instrumental(): returns the Gregorian Calendar date corresponding to the date
from datetime import date
today =
print('today:', today)
print('.year:', today.year)
print('.month:', today.month)
print('.replace():', today.replace(year=2017) )
print('.weekday():', today.weekday())
print('.isoweekday():', today.isoweekday())
print('.isocalendar():', today.isocalendar())
print('.isoformat():', today.isoformat())
print('.strftime():', today.strftime('%Y-%m-%d') )
print('.toordinal():', today.toordinal())

Execution results:

today: 2016-09-12
.year: 2016
.month: 9
.replace(): 2017-09-12
.weekday(): 0
.isoweekday(): 1
.isocalendar(): (2016, 37, 1)
.isoformat(): 2016-09-12
.strftime(): 2016-09-12
.toordinal(): 736219

Date also overloads some operations, which allows us to perform the following operations on the date:

  • date2 = date1 + timedelta # date plus an interval to return a new date object
  • date2 = date1 – timedelta # date minus an interval to return a new date object
  • timedelta = date1 – date2 # two dates are subtracted to return a time interval object
  • Date1 < date2 # two dates are compared

time class

The constructor of the time class is as follows: (where the parameter tzinfo represents the time zone information.)

class datetime.time(hour[, minute[, second[, microsecond[, tzinfo]]]])

Class properties defined by time class:

  • Min, Max: the minimum and maximum time that can be represented by the time class. Where time.min = time(0, 0, 0, 0), time.max = time(23, 59, 59, 999999)
  • resolution: the smallest unit of time, here is 1 microsecond

Instance methods and properties provided by the time class:

  • . hour,. Minute,. Second,. Microsecond: hour, minute, second, microsecond
  • . tzinfo: time zone information
  • . replace([hour[, minute[, second[, microsecond[, tzinfo]]]): create a new time object and replace the attributes in the original object with the hours, minutes, seconds and microseconds specified by the parameters (the original object remains unchanged);
  • . isoformat(): return type, such as string representation in "HH:MM:SS" format;
  • . strftime(fmt): returns a custom format string.

Like date, you can also compare two time objects or subtract to return a time interval object. No examples are provided here.

datetime class

Datetime is a combination of date and time, including all information of date and time. Its constructor is as follows: datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]). The meaning of each parameter is the same as that in the constructor of date and time. Pay attention to the range of parameter values.

Class properties and methods defined by datetime class:

  • min, max: the minimum and maximum values that datetime can represent;
  • resolution: the smallest unit of datetime;
  • today(): returns a datetime object representing the current local time;
  • now([tz]): returns a datetime object representing the current local time. If the parameter tz is provided, the local time of the time zone indicated by the tz parameter is obtained;
  • utcnow(): returns a datetime object of the current utc time;
  • From time stamp (timestamp [, tz]): create a datetime object according to the time stamp, and the parameter tz specifies the time zone information;
  • UTC fromtimestamp (timestamp): create a datetime object according to the time;
  • combine(date, time): create a datetime object based on date and time;
  • strptime(date_string, format): converts the format string to a datetime object;
from datetime import datetime
import time
print('datetime.max:', datetime.max)
print('datetime.min:', datetime.min)
print('datetime.resolution:', datetime.resolution)
print('utcnow():', datetime.utcnow())
print('fromtimestamp(tmstmp):', datetime.fromtimestamp(time.time()))
print('utcfromtimestamp(tmstmp):', datetime.utcfromtimestamp(time.time()))

Operation results:

datetime.max: 9999-12-31 23:59:59.999999
datetime.min: 0001-01-01 00:00:00
datetime.resolution: 0:00:00.000001
today(): 2016-09-12 19:57:00.761000
now(): 2016-09-12 19:57:00.761000
utcnow(): 2016-09-12 11:57:00.761000
fromtimestamp(tmstmp): 2016-09-12 19:57:00.761000
utcfromtimestamp(tmstmp): 2016-09-12 11:57:00.761000

The instance methods and attributes provided by the datetime class (many attributes or methods have appeared in date and time and have similar meanings here. Only these method names are listed here. The specific meanings are not introduced one by one. Please refer to the explanation of date and time classes above.):


  • date(): get the date object;
  • time(): get the time object;
  • replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]]):
  • timetuple()
  • utctimetuple()
  • toordinal()
  • weekday()
  • isocalendar()
  • isoformat([sep])
  • ctime(): returns a C format string of date and time, equivalent to CTime (time. Mktime (DT. Timetuple());
  • strftime(format)

Like date, you can also compare two datetime objects, or subtract to return a time interval object, or date time plus an interval to return a new date time object.

timedelta class

The timedelta function returns a timedelta object, that is, an object representing a time interval. The function parameters are as follows:

class datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])

There are no mandatory parameters. If you simply control, the first integer means the interval of days:


Two time interval objects can be added or subtracted from each other, and still a time interval object is returned. More conveniently, if a datetime object subtracts a time interval object, the corresponding subtracted datetime object will be returned, and then if two datetime objects are subtracted, a time interval object will be returned. This is very convenient.

tzinfo class

Tzinfo is an abstract class and cannot be instantiated directly. You need to generate subclasses and provide corresponding standard methods. The datetime module does not provide any subclasses of tzinfo. The simplest way is to use the pytz module.

pytz module

pytz is a time zone processing module of Python (also including daylight saving time). Before understanding the time zone processing module, you need to understand some concepts of time zone.

To know the conversion relationship between time zones, in fact, it is very simple: subtract the local time zone from the local time zone, and the rest is Greenwich mean time. For example, 18:00 Beijing time is 18:00 + 08:00. After subtraction, it is 10:00 + 00:00, so it is 10:00 GMT.

Python's datetime can handle two types of time: offset naive and offset aware. The former refers to the time without time zone information, and the latter refers to the time with time zone information. Only the same type of time can be subtracted and compared.

By default, the functions of the datetime module only generate datetime objects of offset naive type, such as now(), utcnow(), fromtimestamp(), utcfromtimestamp(), and strftime(). Now () and fromtimestamp () can accept a tzinfo object to generate a datetime object of offset aware type, but the standard library does not provide any implemented tzinfo classes, so they can only be implemented by themselves.

The following is an example of the tzinfo class that implements Greenwich mean time and Beijing time:

ZERO_TIME_DELTA = timedelta(0)
LOCAL_TIME_DELTA = timedelta(hours=8) # Local time zone deviation
class UTC(tzinfo):
    def utcoffset(self, dt):
        return ZERO_TIME_DELTA
    def dst(self, dt):
        return ZERO_TIME_DELTA
class LocalTimezone(tzinfo):
    def utcoffset(self, dt):
        return LOCAL_TIME_DELTA
    def dst(self, dt):
        return ZERO_TIME_DELTA
    def tzname(self, dt):
        return '+08:00'

A tzinfo class needs to implement three methods: utoffset, dst and tzname. Among them, utoffset needs to return the TDOA adjustment of summer time; Tzname needs to return the time zone name. If you don't need to use it, it can also not be implemented.

Once an offset aware datetime object is generated, we can call its astimezone () method to generate the time of other time zones (calculated according to the time difference). If you get an offset naive datetime object, you can also call its replace() method to replace tzinfo, but this replacement will not adjust other time attributes according to the time difference. Therefore, if you get an offset naive datetime object of Greenwich mean time, you can directly call replace(tzinfo=UTC()) to convert it to offset aware, and then call astimezone() to generate datetime objects of other time zones.

It seems that everything is very simple, but I don't know if you still remember the summer season mentioned above. It really gives me a headache to mention the summer season, because it has no rules to follow: some countries implement the summer season, some countries do not implement it, some countries only implement the summer season in some regions, and some regions only implement the summer season in some years. The starting and ending time of the summer season in each region is not necessarily the same, In addition, in some places, the TMD does not use a few months and days to specify the start and end time of summer time, but the first few weeks of a month.

Pytz module uses Olson TZ Database to solve the consistency problem of cross platform time zone calculation and the calculation problem caused by daylight saving time. Since countries and regions can choose their own time zone and whether to use daylight saving time, pytz module has to update their own time zone and daylight saving time related information if necessary.

pytz provides all the timezone information, such as:

import pytz

Operation results:


If you need to obtain the time zone of a country, you can use the following methods:

import pytz

Execution results:

[u'Asia/Shanghai', u'Asia/Urumqi']

China has two time zones, one for Shanghai and the other for Urumqi. Let's see the difference between us:

from datetime import datetime
import pytz
tz1 = pytz.timezone(pytz.country_timezones('cn')[0])
tz2 = pytz.timezone(pytz.country_timezones('cn')[1])

Execution results:

[u'Asia/Shanghai', u'Asia/Urumqi']
2016-09-14 09:55:39.384000+08:00
2016-09-14 07:55:39.385000+06:00

You can see that Shanghai is the eighth East District and Urumqi is the Sixth East District.

Time zone conversion

The operation is simple and convenient. The mutual transfer between local time zone and UTC:

from datetime import datetime
import pytz
now =
tz = pytz.timezone('Asia/Shanghai')

Execution results:

2016-09-14 10:25:44.633000+08:00
2016-09-14 02:25:44.633000+00:00

Use astimezone() to convert between time zones.

from datetime import datetime
import pytz
utc = pytz.utc
beijing_time = pytz.timezone('Asia/Shanghai')
japan_time = pytz.timezone('Asia/Tokyo')
now =
print("Beijing Time:",now)
print("JAPAN TIME:",now.astimezone(japan_time))

Execution results:

Beijing Time: 2016-09-14 10:19:22.671000+08:00
UTC: 2016-09-14 02:19:22.671000+00:00
JAPAN TIME: 2016-09-14 11:19:22.671000+09:00

In addition, you can use replace to modify the time zone. The time zone is 6 minutes longer (do not use it). The specific reasons are:

In the 17th year of the Republic of China (1928), the national government unified China, and the business of the former central observatory was received by the Institute of astronomy and the Institute of Meteorology of the Central Research Institute of the Nanjing government. The almanac compiled by the Institute of astronomy basically follows the practice of the central observatory and still divides the whole country into five standard time zones. Only in places related to Jiaoqi, Heshuo and the time of the sun, the local peacetime of Peiping is no longer used, but replaced by the regional time of the standard time zone where Nanjing is located, that is, 120 ° east longitude standard time. When the standard of Beiping is changed to 120 ° east longitude, the difference between the two is 352 seconds.

from datetime import datetime
import pytz
now =
tz = pytz.timezone('Asia/Shanghai')

Execution results:

2016-09-14 10:29:20.200000
2016-09-14 10:29:20.200000+08:06

Daylight saving time processing

Since there are few scenes used, detailed learning is not required.

dateutil module

Installation module: PIP install Python dateutil


Parsing time to datetime format supports most time strings. If no time is specified, the default is 0:00, if no date is specified, the default is today, and if no year is specified, the default is this year.

from dateutil import parser
print(parser.parse("8th March,2004"))
print(parser.parse("8 March,2004"))
print(parser.parse("March 8th,2004"))
print(parser.parse("March 8,2004"))
print(parser.parse("Wed, Nov 12"))

Execution results:

2004-03-08 00:00:00
2004-03-08 00:00:00
2004-03-08 00:00:00
2004-03-08 00:00:00
2016-09-14 00:00:00
2016-09-14 00:00:00
2016-09-14 00:00:00
2016-09-14 00:00:00
2016-09-09 00:00:00
2016-09-14 12:00:00
2016-11-12 00:00:00


Main function: generate date and time according to rules. The function prototype is as follows.

rrule(self, freq, dtstart=None, interval=1, wkst=None, count=None, until=None, bysetpos=None, bymonth=None, bymonthday=None, byyearday=None, byeaster=None, byweekno=None, byweekday=None, byhour=None, byminute=None, bysecond=None, cache=False)

Of which:

  • freq: it can be understood as a unit. It can be year, monthly, weekly, daily, hourly, minutely, secondary. That is, mm / DD / YY, weekly hours, minutes and seconds.
  • dtstart,until: is the start and end time.
  • wkst: week start time.
  • Interval: interval.
  • count: specifies how many are generated.
  • byxxx: specify the matching period. For example, byweekday=(MO,TU) only matches Monday and Tuesday. Byweekday can specify MO,TU,WE,TH,FR,SA,SU. Monday to Sunday.

More references:


Arrow provides a friendly and easy to understand method for creating time, calculating time and formatting time. It can also convert, extract and be compatible with python datetime type. It includes the dateutil module. According to its documentation, arrow is designed to "help you deal with dates and times with less code".

UTC time

Use the utcnow() function to create UTC time.

Using the to() method, we convert UTC time to local time.

import arrow
utc = arrow.utcnow()

local time

Local time is the time in a specific region or time zone.

import arrow
now =

Use the now() function to create a local time. The to() method is used to convert local time to UTC time.

Resolution time

The get() method is used to parse the time.

import arrow
d1 = arrow.get('2012-06-05 16:20:03', 'YYYY-MM-DD HH:mm:ss')
d2 = arrow.get(1504384602)

This example parses time from date and time strings and timestamps.

Unix timestamp

import arrow
utc = arrow.utcnow()
unix_time = utc.timestamp
date = arrow.Arrow.fromtimestamp(unix_time)

This example shows local time and Unix time. It then converts Unix time back to the date object.

Using the fromtimestamp() method, we convert Unix time back to the Arrow Date object.

You can also format the date as a Unix time.

import arrow
utc = arrow.utcnow()

By passing the 'X' specifier to the format() method, we print the current local date as a Unix time.

Format date and time

The date and time can be formatted with the format() method.

import arrow
now =
year = now.format('YYYY')
print("Year: {0}".format(year))
date = now.format('YYYY-MM-DD')
print("Date: {0}".format(date))
date_time = now.format('YYYY-MM-DD HH:mm:ss')
print("Date and time: {0}".format(date_time))
date_time_zone = now.format('YYYY-MM-DD HH:mm:ss ZZ')
print("Date and time and zone: {0}".format(date_time_zone))

Format Description:

Convert to area time

import arrow
utc = arrow.utcnow()


The weekday() or format() method can be used to find the working day of the date.

import arrow
d1 = arrow.get('1948-12-13')

Moving time

The shift() method is used to move the time.

import arrow
now =

Daylight saving time

import arrow
now =
print(now.format("YYYY-MM-DD HH:mm:ss ZZ"))

This example uses dst() to display daylight saving time.

Humanized date and time

On social networking sites, we can often see terms such as "an hour ago" or "5 minutes ago". These terms can provide people with quick information about the time when posts were created or modified. Arrow contains the humanize() method to create such terms.

import arrow
now =
d1 = now.shift(minutes=-15).humanize()
d2 = now.shift(hours=5).humanize()

ISO 8601 class

International standard ISO 8601 is the date and time representation method of the international organization for standardization. Its full name is data storage and exchange form · information exchange · date and time representation method. It is more involved in API interface development.

>>> import dateutil.parser
>>> dateutil.parser.parse('2008-09-03T20:56:35.450686Z') # RFC 3339 format
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=tzutc())
>>> dateutil.parser.parse('2008-09-03T20:56:35.450686') # ISO 8601 extended format
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686)
>>> dateutil.parser.parse('20080903T205635.450686') # ISO 8601 basic format
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686)
>>> dateutil.parser.parse('20080903') # ISO 8601 basic format, date only
datetime.datetime(2008, 9, 3, 0, 0)

Or use the following method:

>>> datetime.datetime.strptime("2008-09-03T20:56:35.450686Z", "%Y-%m-%dT%H:%M:%S.%fZ")

You can also use the iso8601 module:

Other date and time tools:

  • Gregorian to lunar calendar
  • Colloquial date
  • Moment
  • Delorean
  • When
  • Pendulum
  • Time machine
  • Shop Calendar
  • Chinese legal holidays