This article summarizes a few date-related uses in Python as notes for later review.

The datetime module is mainly used. The date class in the Datetime module contains year, month and day, while the time class contains hour, minute, second, microsecond and time zone. The Datetime class is a combination of date and time, including year, month, day, hour, minute, second, microsecond and time zone.

String ⇋ date

Strftime is used to convert dates to strings, and strptime is used to convert dates to strings. The differences are as follows:

strftime strptime
use Converts an object to a string based on the given format Converts a string to a given corresponding formatdatetimeobject
Type of method Instance methods Class method
Who has the method date; datetime; timeThe instance datetimeclass
Use your strftime(format) strptime(date_string, format)

Date transfer string

Use strftime(format), and note that this is the instance method.

1. Convert the date instance to a string:

from datetime import date

today = date.today()
today_str = today.strftime('%Y-%m-%d')
print(today_str) # 2021-06-14
Copy the code

For the meaning of symbols such as %Y used to represent year, month, day, etc., see: format codes.

2. Datetime class instance converted to string:

from datetime import datetime

dt = datetime(2021.6.14.15.2.3)
dt_str = dt.strftime('%Y/%m/%d %H:%M:%S')
print(dt_str) # 2021/06/14 15:02:03
Copy the code

Constructor datetime.datatime, which creates an instance of datetime. Usage:

datetime.datetime(year, month, day, hour=0,minute=0,second=0, microsecond=0,tzinfo=None, *, fold=0)
Copy the code

3. The time instance is converted to a string

from datetime import time

t = time(15.3.0)
t_str = t.strftime('%H:%M:%S')
print(t_str) # 15:03:00
Copy the code

String transfer date

Use strptime(date_string, format). Note that this is a class method.

from datetime import datetime

dt = datetime.strptime('2021/06/14 15:05:06'.'%Y/%m/%d %H:%M:%S')
print(dt, type(dt)) # 2021-06-14 15:05:06 <class 'datetime.datetime'>
Copy the code

Time interval calculation

Dateutil packages make date-related processing very easy, and you can also use python’s own modules.

Get the date time based on the time interval

Get the start time n seconds/minutes/hours/days/weeks/months/years from the current time.

Method 1: Use Python’s built-in modules

The timedelta method of the main Datetime module. Timedelta represents a time interval, the difference between two dates or times. Usage:

datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Copy the code

Implementation code:

import calendar
from datetime import datetime, timedelta

def get_start_time(time_number, time_unit) :
    Time_number Time in seconds/min/hour/day/week/month/year
    if type(time_number) ! =int or type(time_unit) ! =str:
        raise Exception('Time_number must be an integer and time_unit must be a string')
    now = datetime.now()
    unit_list = ['seconds'.'minutes'.'hours'.'days'.'weeks']
    delta_params = None
    if time_unit in unit_list:
        delta_params = {
            time_unit: time_number
        }
        delta = timedelta(**delta_params)
        start_time = now - delta
        return start_time
    if time_unit == 'months':
        now_year = now.year
        now_month = now.month
        now_day = now.day
        start_year = now_year
        start_month = now_month - time_number
        start_day = now_day
        For example, if the current date is March 2021, the previous date would be October 2020
        if start_month <= 0:
            months_interval = abs(start_month)
            years_interval = months_interval // 12
            start_year = now_year - years_interval - 1
            start_month = 12 - months_interval % 12

        weekday, month_days = calendar.monthrange(year=start_year, month=start_month)
        For example, if today is March 31st and February is only February 28th, the last day of February will be the 28th
        if now_day > month_days:
            start_day = month_days
        start_time = now.replace(year=start_year, month=start_month, day=start_day)
        return start_time
    
    if time_unit == 'years':
        now_year = now.year
        now_month = now.month
        now_day = now.day
        start_year = now_year - time_number
        start_day = now_day
        weekday, month_days = calendar.monthrange(year=start_year, month=now_month)
        # the month before time_number does not have the current date, for example, today is February 29, and February 28 is February 28 in the previous year
        if now_day > month_days:
            start_day = month_days
        start_time = now.replace(year=start_year, month=now_month, day=start_day)
        return start_time

# test
x = get_start_time(1.'years')
print(x)
Copy the code

1. Because the timedelta method only supports up to weeks, the calculation of months and years needs to be handled by ourselves, taking into account the special case of cross year and date.

2. Datetime and date instances both have replace methods, which are used as follows:

Return a date instance:

date.replace(year=self.year, month=self.month, day=self.day)
Copy the code

For example, to replace today’s year with 2020, you can use:

from datetime import date

today = date.today()
n = today.replace(year=2020)
print(n) # 2020-06-14
Copy the code

(2) Return datetime instance:

datetime.replace(year=self.year, month=self.month, day=self.day, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, tzinfo=self.tzinfo, *, fold=0)
Copy the code

For example, to replace today’s month with May, you can use:

from datetime import datetime

now = datetime.now()
m = now.replace(month=5)
print(m) # 2021-05-14 16:27:44. 384520
Copy the code

3. The calendar.monthrange(year, month) method of the calendar module returns the working day of the first day of the specified month and the total number of days in that month.

Method two: Usedateutilpackage

PIP install python-dateutil.

Use the relativedelta method.

relativedelta.relativedelta(years, months, weeks, days, hours, minutes, seconds, microseconds)
Copy the code

Implementation code:

from dateutil.relativedelta import relativedelta

def get_start_time_v1(time_number, time_unit) :
    unit_list = ['years'.'months'.'weeks'.'days'.'hours'.'minutes'.'seconds']
    if type(time_number) ! =int:
        raise Exception('The incoming time_number type must be an integer')
    if time_unit not in unit_list:
        raise Exception('Incorrect unit time_unit passed in')
    now = datetime.now()
    delta_params = {
        time_unit: -time_number
    }
    start_time = now + relativedelta(**delta_params)
    return start_time

# test
y = get_start_time_v1(1.'years')
print(y)
Copy the code

To get the prior 2 month interval, use:

relativedelta.relativedelta(months=-2)
Copy the code

To get an interval of 2 months and 2 days, use:

relativedelta.relativedelta(months=-2, days=-2)
Copy the code

Get the interval based on the date time

Count the number of seconds between two times.

def get_time_interval(start_time, end_time) :
    start_time = datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S')
    end_time = datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S')
    if type(start_time) ! = datetimeor type(end_time) ! = datetime:raise Exception('Invalid format of argument passed in')
    if end_time < start_time:
        raise Exception('End time less than start time')
    interval = end_time - start_time
    return interval.seconds

# test
z = get_time_interval('the 2021-06-14 14:55:00'.'the 2021-06-14 14:55:02')
print(z) # 2 seconds,
Copy the code

Properties of timedelta instance:

attribute value
days -999999999 to 99999999999, including 99999999999
seconds 0 to 86399, including 86399
microseconds 0 to 999999, including 999999

If you want to calculate the year difference or month difference between two dates instead of counting the seconds of two times, it’s convenient to use the Relativedelta method:

def get_time_interval_v1(start_time, end_time) :
    start_time = datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S')
    end_time = datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S')
    if type(start_time) ! = datetimeor type(end_time) ! = datetime:raise Exception('Invalid format of argument passed in')
    if end_time < start_time:
        raise Exception('End time less than start time')
    interval = relativedelta(end_time, start_time)
    return interval.years * 12 + interval.months
    
o = get_time_interval_v1('the 2021-06-14 14:55:00'.'the 2022-07-14 14:55:02')
print(o) # 13 month
Copy the code

The source address

Github.com/renmo/myBlo…