# Detailed explanation of Python date conversion and calculation

Time：2020-10-24

For dates, sometimes it is necessary to perform a conversion of different time units, or to accept a date in string format and convert it into a datetime object. Sometimes you need to calculate the range of dates, as well as the dates of a particular day of the week. The datetime module provided by Python is more used here.

Datetime module

Simple conversion of date and time

In the datetime module, a time period can be represented by creating a timedelta object. Examples are as follows:

``````
>>> from datetime import timedelta
>>> a = timedelta(days=2, hours=6)
>>> b = timedelta(hours=4.5)
>>> c = a + b
>>> c
datetime.timedelta(2, 37800)
>>> c.days
2
>>> c.seconds
37800
>>> c.seconds / 3600
10.5
>>> c.total_seconds() / 3600
58.5
``````

If you want to represent the specified date and time, you need to create a datetime object and then perform the operation using standard mathematical operations. Examples are as follows:

``````
>>> from datetime import datetime
>>> a = datetime(2020, 1, 15)
>>> print(a + timedelta(days=10))
2020-01-25 00:00:00
>>> b = datetime(2020, 2, 3)
>>> d = b - a
>>> d
datetime.timedelta(19)
>>> d.days
19
>>> now = datetime.today()
>>> print(now)
2020-01-15 10:59:10.230995
>>> print(now + timedelta(minutes=10))
2020-01-15 11:09:10.230995
``````

The datetime object can handle leap year problems on its own, as shown in the following example:

``````
>>> a = datetime(2020, 3, 1)
>>> b = datetime(2020, 2, 28)
>>> a - b
datetime.timedelta(2)
>>> (a - b).days
2
>>> c = datetime(2019, 3, 1)
>>> d = datetime(2019, 2, 28)
>>> c - d
datetime.timedelta(1)
>>> (c - d).days
1
``````

Conversion between string and date

When the written program accepts the date input expressed in string format, it needs to convert such string into datetime object for calculation.

Use the strptime() method in the datetime object, as shown in the following code:

``````
>>> from datetime import datetime
>>> text = '2020-01-15'
>>> y = datetime.strptime(text, '%Y-%m-%d')
>>> y
datetime.datetime(2020, 1, 15, 0, 0)
>>> z = datetime.now()
>>> z
datetime.datetime(2020, 1, 15, 11, 10, 11, 71792)
>>> diff = z-y
>>> diff
datetime.timedelta(0, 40211, 71792)
``````

The above meaning of% y is the year with century in decimal system,% m is the month expressed in decimal system after zero padding, and% d is the day in the month expressed in decimal system after zero padding.

Here are some format codes. For example:

instructions meaning
%a Abbreviation for local working day
% A Full name of local working day
% b Abbreviation for local month
% B Full name of local month
% H Decimal hour after zero padding (24-hour system)
% I Decimal hour after zero padding (12 hour system)
% M Decimal minutes after zero padding
% S Decimal seconds after zero padding

Format the date as follows:

``````
>>> z
datetime.datetime(2020, 1, 15, 11, 10, 11, 71792)
>>> format_z = datetime.strftime(z, "%A %B %d, %Y")
>>> format_z
'Wednesday January 15, 2020'
``````

datetime.strftime The () function returns a string representing the date specified by the display format string. Format instruction, such as% a% B% d% Y in the above code. Where the first parameter of the function is the datetime object.

What needs to be noted here is that the performance of strptime is relatively poor. If the explicit requirement is to parse a large number of date strings with known format, you can consider implementing a set of parsing scheme yourself. Assuming the format is yyyy-mm-dd, the following code can be used to implement the parsing function:

``````
from datetime import datetime
def parse_ymd(s):
year_s, mon_s, day_s = s.split('-')
return datetime(int(year_s), int(mon_s), int(day_s))
``````

The effects of the two methods are as follows:

``````
In : from datetime import datetime
...: def parse_ymd(s):
...:   year_s, mon_s, day_s = s.split('-')
...:   return datetime(int(year_s), int(mon_s), int(day_s))

In : text = "2020-01-15"

In : %timeit datetime.strptime(text, '%Y-%m-%d')
7.75 µs ± 31 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In : %timeit parse_ymd(text)
1.05 µs ± 3.07 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

``````

As you can see, parse_ Ymd() function ratio datetime.strptime () more than 7 times faster. If the design date with a large amount of processing and the format is fixed, this scheme can be considered.

Calculate the date range for a month

The calendar module provided by Python provides calendar related functions. You can consider the implementation requirements with the datetime module

``````#!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
@File: datetime_calendar.py
@Time: 2020/01/15 12:46:58
@Author: a dream of three thousand years
@Contact: [email protected]
'''

# put the import lib here
from datetime import date, timedelta
import calendar

def get_month_range(start_date=None):
'''get the range of the month

Args:
start_ Date: the start date. The default value is none

Returns:
Returns a tuple containing the start and end dates of the month
'''
if start_ Date is none: if start_ Date is empty and assigned as the first day of the month
start_date = date.today().replace(day=1)
#Gets the number of days of the month
_, days_in_month = calendar.monthrange(start_date.year, start_date.month)
#Calculation end date
end_date = start_date + timedelta(days=days_in_month)
#Returns a tuple of start and end dates
return (start_date, end_date)``````

Use the following in the interactive interpreter:

``````
In : from datetime import timedelta

In : from datetime_calendar import get_month_range

In : a_day = timedelta(days=1)

In : first_day, last_day = get_month_range()

In : while first_day < last_day:
...:   print(first_day)
...:   first_day += a_day
...:
2020-01-01
2020-01-02
2020-01-03
2020-01-04
2020-01-05
2020-01-06
2020-01-07
2020-01-08
...

``````

Note: if you can’t import methods in your own module under the interactive interpreter, try to open the interactive interpreter directly in the path where the file is located.
In the above code, start first_ Date is calculated according to the first day of the month. Here we use the replace() method of the date object to set the day property to 1, which means the first day.

calendar.monthrange The () function returns the day of the week on the first day of the specified month in the specified year and the number of days in the month.

After obtaining the month days, add the start date to get the end date. It should be noted that the end date is not included in this date range. When traversing, the condition is first_ day < last_ Day, do not output last_ The value of day, which is incremented by the timedelta instance.

reference material

source

1. David M. Beazley;Brian K. Jones.Python Cookbook, 3rd Edtioni.O’Reilly Media.2013.
2. “8.1. datetime — Basic date and time types”.docs.python.org.Retrieved 11 January 2020
3. “8.2. calendar — General calendar-related functions”.docs.python.org.Retrieved 13 January 2020