python -- datetime library usage

The datetime module is a collection of date and time modules. Datetime has two constants, maxear and MINYEAR, which are 9999 and 1 respectively

Time and date formatting symbols in python:

%y two digit year representation (00-99)
%Y four digit year (000-9999)
%m month (01-12)
%Day of the month (0-31)
%H 24-hour system hours (0-23)
%I 12 hour system hours (01-12)
%M minutes (00 = 59)
%S seconds (00-59)
%a local simplified week name
%A local full week name
%b local simplified month name
%B local full month name
%c local corresponding date representation and time representation
%One day in j years (001-366)
%P equivalent of local A.M. or P.M
%U number of weeks in a year (00-53) Sunday is the beginning of the week
%w week (0-6), Sunday is the beginning of the week
%W number of weeks in a year (00-53) Monday is the beginning of the week
%x local corresponding date representation
%X local corresponding time representation
%Z name of the current time zone
%%% sign itself

The datetime module defines five classes

datetime.date: class representing date -- Date object

datetime.date(year,month,day), return year month day

print(datetime.date(2021,9,13))
result:
2021-09-13

datetime.date.today(), get the year, month and day of the current day, and return year month day

print(datetime.date.today())
result:
2021-09-13

a = datetime.date.today()
print(a.year)
print(a.month)
print(a.day)
result:
2021
9
13

datetime.date.isocalendar(), so that the date used conforms to the ISO standard, and returns a tuple containing three values: year year, week number, weeks (Monday is 1... Sunday is 7)

print(datetime.date.today().isocalendar())
result:
(2021, 37, 1)

datetime.date.isoformat(), return the date string conforming to ISO 8601 standard (YYYY-MM-DD);

print(datetime.date.today().isoformat())
result:
2021-09-13

datetime.date.isoweekday(): returns the number of weeks (Monday is 1... Sunday is 7) of the specified date conforming to the ISO standard

print(datetime.date.today().isoweekday())
result:
1

datetime.date.strftime(format): format the date and time according to the given format.

print(datetime.date.today().strftime("%Y %m %d"))
result:
2021 09 13

datetime.date.ctime(), returns the time format in English. The standard format is Mon Sep 13 00:00:00 2021

print(datetime.date.today().ctime())
result:
Mon Sep 13 00:00:00 2021

datetime.datetime: class representing date and time - date and time object (most commonly used)

datetime class is actually a combination of date class and time class. Most of its methods and properties are inherited from these two classes
The datetime class has many parameters. datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]) returns year, month, day, hour, minute and second

datetime.datetime.now(): returns the current system time

print(datetime.datetime.now())
result:
2021-09-13 23:08:13.415655

datetime.datetime.ctime() converts datetime.datetime type to str type, output: Sun Jul 28 15:47:51 2019

print(datetime.datetime.now().ctime())
result:
Mon Sep 13 23:08:44 2021

datetime.datetime.now().date(): returns the date part of the current date and time

print(datetime.datetime.now().date())
result:
2021-09-13

datetime.datetime.now().time(): returns the time part of the current date and time

print(datetime.datetime.now().time())
result:
23:10:54.719265

Datetime. Datetime. Utctimetaple(): returns the UTC time tuple

print(datetime.datetime.now().utctimetuple())
result:
time.struct_time(tm_year=2021, tm_mon=9, tm_mday=13, tm_hour=23, tm_min=11, tm_sec=52, tm_wday=0, tm_yday=256, tm_isdst=0)

datetime.datetime.combine(date,time): merge a date object and a time object to generate a datetime object:

a = datetime.datetime.now()
print(datetime.datetime.combine(a.date(),a.time()))
result:
2021-09-13 23:14:31.712160

datetime.datetime.strftime(format): convert from date format to string format

print(datetime.datetime.now().strftime('%b-%d-%Y %H:%M:%S'))
result:
Sep-13-2021 23:20:10

datetime.datetime.strptime(string, format): convert from string format to date format

print(datetime.datetime.strptime('Sep-13-2021 23:20:10', '%b-%d-%Y %H:%M:%S'))
result:
2021-09-13 23:20:10

datetime.time: class representing time -- time object

The time class consists of hour hour, minute minute, second second, microsecond millisecond and tzinfo
time([hour[, minute[, second[, microsecond[, tzinfo]]]]])

>>> a = datetime.time(12,20,59,899)
>>> a
datetime.time(12, 20, 59, 899)
>>> a.hour
12
>>> a.minute
20
>>> a.second
59
>>> a.microsecond
899

1.datetime.time.replace()
2.datetime.time.strftime(format): returns the time in format format
3.datetime.time.tzname(): returns the name of the time zone
4. Datetime. Time. Utoffset(): returns the time offset of the time zone

datetime.timedelta: represents the time interval, that is, the interval between two time points

The timedelta class is used to calculate the difference between two datetime objects.
This class contains the following attributes:
1. Days: days
2. Microseconds: microseconds (> = 0 and < 1 second)
3. Seconds: seconds (> = 0 and < 1 day)
days, seconds, microseconds, milliseconds, minutes, hours, weeks, and the default value is 0.

#Find the time two days and ten hours ahead of the current time
delta = datetime.timedelta(days = 2,hours = 2)
print(datetime.datetime.now())
print(datetime.datetime.now()-delta)
result:
2021-09-14 11:40:27.702018
2021-09-12 09:40:27.702018

datetime.tzinfo: information about time zone

To be added, I think it's useless

Date calculation practice

Gets the date, hour, minute and second of the time of the day

#Gets the date, hour, minute and second of the time of the day
print(datetime.datetime.now())
#Get the date, hour, minute and second of the time of the day method 1
print(datetime.datetime.now().date())
#Get the date, hour, minute and second of the time of the day method 2
print(datetime.date.today())
#Gets the date, hour, minute and second of the time of the day
print(datetime.datetime.now().time())
result:
2021-09-14 11:52:52.459443
2021-09-14
2021-09-14
11:52:52.459443

Gets the date of the first and last day of the previous month

# Get the date of the current time first
today = datetime.date.today()
# Subtract one day from the last day of the previous month, that is, the first day of the current month
lastday = datetime.date(today.year,today.month,1)-datetime.timedelta(days=1)
# First day of last month 
firstday = datetime.date(today.year,today.month-1,1)
print(lastday)
print(firstday)
result:
2021-08-31
2021-08-01

Get time difference

start = datetime.datetime.now()
time.sleep(2)
end = datetime.datetime.now()
print((end - start).seconds)
result:
2

Find the time two days and ten hours ahead of the current time

You can calculate: days, hours, minutes, seconds, and microseconds

delta = datetime.timedelta(days = 2,hours = 2)
print(datetime.datetime.now())
print(datetime.datetime.now()-delta)
result:
2021-09-14 11:40:27.702018
2021-09-12 09:40:27.702018

Calculate the date of the last day of the month and the number of days of the month on the specified date

# Calculate the last day of the current month, i.e. the first day of the next month - day 1
def eomonth(date_object):
    # First, we have to judge whether the current time is the last month of each year
    if date_object.month == 12:
         # In December, year+1 and month is 1
        next_month_first_date = datetime.date(date_object.year+1,1,1)
    else:
        # If it is not December, then month+1
        next_month_first_date = datetime.date(date_object.year, date_object.month+1, 1)
    return next_month_first_date - datetime.timedelta(1)

date = datetime.date.today()
print(eomonth(date))
print(eomonth(date).day)
result:
2021-09-30
30

Calculates the date of the month following the specified date

# Calculate the last day of the current month, i.e. the first day of the next month - day 1
def eomonth(date_object):
    # First, we have to judge whether the current time is the last month of each year
    if date_object.month == 12:
         # In December, year+1 and month is 1
        next_month_first_date = datetime.date(date_object.year+1,1,1)
    else:
        # If it is not December, then month+1
        next_month_first_date = datetime.date(date_object.year, date_object.month+1, 1)
    return next_month_first_date - datetime.timedelta(1)
#Calculates the date of the month following the specified date
def edate(date_object): 
    # First, we have to judge whether the current time is the last month of each year
    if date_object.month == 12:    
        # In December, year+1, month is 1, and day is date_object.day. In any case, date_object.day is 31 or less in January, and there will be no bug s in 31 days
        next_month_date = datetime.date(date_object.year+1, 1,date_object.day)
    else:
        # If it is not December, it needs to be discussed by situation, because there are large and small months. This month has the 31st day, but the next month does not necessarily have the first day of the next month
        next_month_first_day = datetime.date(date_object.year,date_object.month+1,1)
        # If the requested date is not in the next month, it will be replaced by the last day of the following month. Here, the function to obtain the number of days in the next month is called
        if date_object.day > eomonth(next_month_first_day).day:
            next_month_date = datetime.date(date_object.year,date_object.month+1,eomonth(next_month_first_day).day)
        else:
            next_month_date = datetime.date(date_object.year, date_object.month+1, date_object.day)
    return next_month_date

date = datetime.date.today()
print(date)
print(edate(date))
result:
2021-09-14
2021-10-14

Obtain the time period from Monday to today and the corresponding time period of last week

today = datetime.date.today()
this_monday = today - datetime.timedelta(today.isoweekday()-1)
last_monday = this_monday - datetime.timedelta(7)
last_weekday = today -datetime.timedelta(7)
print(this_monday)
print(today)
print(last_monday)
print(last_weekday)
result:
2021-09-13
2021-09-14
2021-09-06
2021-09-07

Tags: Python

Posted on Sun, 19 Sep 2021 17:12:56 -0400 by jeroom