current position:Home>Datetime of Python time operation (Part I)

Datetime of Python time operation (Part I)

2022-01-30 17:33:25 Little cute in the circle of friends

Little knowledge , Great challenge ! This article is participating in “ A programmer must have a little knowledge ” Creative activities .

This article has participated in  「 Digging force Star Program 」 , Win a creative gift bag , Challenge creation incentive fund .


Python The built-in library for time operation provides time Module and datetime modular .

  • time modular The structural time, timestamp and string time are converted to each other, and the related methods are learned
  • datetime The module provides a variety of processing time and date , Easy and convenient

python It also provides general calendar related methods calendar modular , Time zone information zoneinfo modular , And third party libraries arrow、dateutil The module deals with time

In this issue , We will learn datetime Learning module related classes and methods ,Let's go~

1. datetime The module overview

datetime The module not only supports the mathematical operation of time and date , It also provides attribute related methods for efficient output formatting and operation

datetime The module divides the date and time into two kinds of perceptual objects and simple objects according to the time zone information

  • Perceptual time object : Make full use of Applied Computing , And the local actual situation to accurately locate the time point , Usually used to indicate a fixed point in time without interpretation space
  • Simple time object : Will not contain local information , It all depends on the time point calculated by the specific program , Ignore reality , It usually represents UTC World standard time

datetime Provide many classes , It can further facilitate us to extract the information of perceptual time objects .

  • date Objects of type are simple
  • time and datetime Objects of type can be perceptual or simple
  • timedelta The object is neither perceptual nor simple

2. datetime Part of the

datetime Module comparison time The difference is , It mainly provides classes of operation date and time .

By looking at datetime Module files mainly provide time and date processing and time zone related classes 6 class

Class name describe Used to represent a date , Common attributes are :year, month and day
datetime.time Used to indicate time , Common attributes are :hour, minute, second, microsecond
datetime.datetime Used to indicate date and time
datetime.timedelta Used to indicate two date、time、datetime The time interval between instances , The smallest unit can reach microseconds
datetime.tzinfo Abstract base class of time zone related information objects . They are created by datetime and time Class uses , Adjust to provide custom time .
datetime.timezone Python 3.2 New features in , Realization tzinfo Classes that abstract base classes , To express with UTC Fixed offset of

datetime Module related class diagram :

datetime The objects of classes in the module are immutable types

date、time These two classes are the most commonly used

3. datetime Constant

stay datetime.pyi In file , We know detetime The module defines two constants

Constant name describe
datetime.MINYEAR or datetime.datetime Object is the minimum number of years allowed , The value is 1
datetime.MAXYEAR or datetime.datetime The maximum number of years allowed by the object , Just for 9999

4. datetime Common methods

datetime Module comparison time The module provides more operation time and date , Below we list the common methods

Method effect
datetime.datetime.timestamp() take datetime Object is converted to output in the form of timestamp Format output current system time
datetime.datetime.timedelta([hours,days]) Set the offset of a property
datetime.datetime.strptime(date_str,format) Convert the time string to datetime object Format the timestamp and output it as date Return local date
datetime.time.strftime(fromat) Returns the formatted output of local time
datetime.time.dst() Return to the local time zone ,tzinfo by none, Then return to none
datetime.tzinfo.utcoffset(dt) Set time zone difference , East is positive , return timedelta object
datetime.tzinfo.dst(dt) Adjust daylight saving time back to a timedelta object

5. A profound

We are right. datetime Module common methods of learning , Let's enter the date to judge whether it is yesterday or today, that is Ture, Otherwise false

def check_current_date(sw_date):
    cur_date_list =  time.strftime("%Y/%m/%d", time.localtime()) .split('/')
    today =
    offset = datetime.timedelta(days=-1)
    yes_data = today+offset
    yes_data_list = yes_data.strftime("%Y/%m/%d").split('/')
    data_list = cur_date_list + yes_data_list
    seps = ['/', '-', '_']
    for sep in seps:
        date_parts= sw_date.split(sep)
        print("cur_date_list = {}, arg sw_date = {}".format(data_list, sw_date))
        if len(date_parts) == 3:
            for data in date_parts:
                if data not in data_list:
                    return False
            return True
    return False
 Copy code 

Let's test the results :

print(" The current date :",
print(" The day before the test :",check_current_date("2021-10-29"))
print(" Test current date :",check_current_date("2021/10/30"))
 Copy code 


In this issue , We are right. datetime Basic understanding of the module , know datetime The module contains 6 Classes , And learn and practice the common methods .

In the future, we will focus on datetime Module each class to learn in detail .

The above is the content of this issue , Welcome big guys to praise and comment , See you next time ~

copyright notice
author[Little cute in the circle of friends],Please bring the original link to reprint, thank you.

Random recommended