• By Han Xinzi @Showmeai
  • Tutorial address: www.showmeai.tech/tutorials/5…
  • This paper addresses: www.showmeai.tech/article-det…
  • Statement: All rights reserved, please contact the platform and the author and indicate the source

Python date and time

In the development of Python, we often have to deal with time type data. Python has built-in standard libraries such as Time and Datetime to help us deal with time type data. In this section, we will focus on these two standard libraries and introduce common methods in detail.

1. Time module

In Python, the time module is primarily used to convert a timestamp to a specific date and time, but the time module represents a date and time object with a simple structure that is not suitable for complex operations and representations.

(1) Module usage

Struct_time only has one class in the time module:

Struct_time is a structured time object converted to seconds. Attributes such as year, month, day, hour, minute, and second can be obtained by subscript or attribute name. Struct_time instances can be obtained by calling gmtime(), localtime(), strptime(), etc.

>>> st = time.localtime()
>>> st
time.struct_time(tm_year=2021, tm_mon=10, tm_mday=27, tm_hour=19, tm_min=27, tm_sec=31, tm_wday=2, tm_yday=300, tm_isdst=0)
>>> st.tm_mon
10
>>> st[1]
10
Copy the code
# Convert between struct_time and string
>>> time.strftime('%H:%M:%S')
'19:10:37'

>>> time.strptime("30 Nov 00"."%d %b %y")   
time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0,
                 tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)
Copy the code
import time

Format to 2021-10-27 19:56:36
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

Format to Sat Mar 28 22:24:24:2016
print(time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()))
 
# convert format string to timestamp
a = "Wed Oct 27 19:56:36 2021"
print(time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y")))
Copy the code

2. A datetime module

The Datetime module supports date and time operations and provides classes for manipulating dates and times. Most of the functionality of this module is implemented around the methods and properties of the following four classes (and two other classes about time zones).

(1)dateClass and usage

The date class represents the date type.

Supported operators:

  • Support with anotherdateThe object of= =.Or less.<.p.>And so on.
  • Support andtimedeltaObject is added or subtracted, and the result is stilldateObject.
  • Support with anotherdateObject subtraction operation, gettimedeltaObject.
  • Support hashing.

Code examples:

Pass in the date argument to instantiate the date class
>>> from datetime import date
>>> date(2021.10.29)
datetime.date(2021.10.29)

Time can be obtained by timestamp
>>> date.fromtimestamp(time.time())
datetime.date(2021.10.29)

>>> d2 = date(2021.10.29)
>>> d1 = date(2021.10.27)
>>> d2 > d1
True
>>> d2 - d1
datetime.timedelta(days=2)
Copy the code

(2)timeClass and usage

The time class represents the time (hour, minute, second) type.

Supported operators

  • Support with anothertimeThe object of= =.Or less.<.p.>And so on.
  • Support hashing.

Code sample

>>> from datetime import time
>>> t = time.fromisoformat('19:32:10')
>>> t.strftime('%Hh %Mm %Ss')
'19h 32m 10s'

>>> t = time(hour=19, minute=27, second=55)
>>> t.isoformat()
'19:27:55'
Copy the code

(3)datetimeClass and usage

The DateTime class represents a time type that contains date times. It can be considered a combination of date and time instances, and therefore has most of the methods and properties of both objects.

Supported operators

  • datetimeSupport anddateI’m going to make an equality comparison, but the result must be zeroFalse, otherwise only supported with anotherdatetimeObject to perform= =.Or less.<.p.>And so on.
  • Support andtimedeltaIf you add them up, you get zerodatetime; Support andtimedeltaObject is added or subtracted, and the result is still zerodatetimeObject, and anotherdatetimeObject subtracts, and you gettimedeltaObject.
  • We also support hashing.

Code sample

>>> from datetime import datetime
>>> datetime(year=2021, month=10, day=29)
datetime.datetime(2021.10.29.0.0)

>>> datetime.now()
datetime.datetime(2021.10.29.14.51.18.731235)

>>> datetime.fromisoformat('the 2021-10-29 16:09:32')
datetime.datetime(2021.10.29.16.9.32)

>>> dt = datetime.now()
>>> dt.timestamp()
1635317544.682565

>>> dt.date()
datetime.date(2021.10.29)
Copy the code

(4)timedelta

The Timedelta class object represents the difference between two DateTime objects.

Supported operators

  • Only comparisons with another timedelta are supported, such as ==, ≤, <, ≥, >.

  • Timedelta object support supports addition and subtraction, and datetime added to or subtracted from timedelta still returns a Datetime.

  • Timedelta also supports operators such as multiply, divide, and modulo.

  • Support hashing.

  • Timedelta is signed and supports the abs() function, which returns the absolute interval between two datetimes.

Code sample

>>> from datetime import timedelta
>>> timedelta(days=2)
datetime.timedelta(days=2)

>>> dt1 = datetime.now()
>>> dt2 = datetime.now()
>>> dt2 -dt1
datetime.timedelta(seconds=4, microseconds=476390)

>>> d = timedelta(minutes=3, seconds=35)
>>> d.total_seconds()
215.0
Copy the code

Information and code download

This series of tutorials can be downloaded from Github on ShowMeAI, which can be run locally in Python. If you can use Google Colab, you can also use Google Colab.

The Python sketchbooks covered in this tutorial series can be downloaded at:

  • Python quick table

Expanded Reference materials

  • Python tutorial – Python3 documentation
  • Python Tutorial – Official website of Liao Xuefeng

ShowMeAI related articles recommended

  • Python is introduced
  • Python installation and environment configuration
  • Basic Python syntax
  • Basic Python data types
  • Python operator.
  • Python conditional control with if statements
  • Python loop statements
  • Python while loop
  • The python for loop
  • Python break statement
  • Python continue statement
  • Python pass statement
  • Python strings and operations
  • Python list
  • The python tuple
  • Python dictionary
  • Python set
  • Python functions
  • Python iterators and generators
  • Python data structures
  • Python module
  • Python file reading and writing
  • Python file and directory operations
  • Python error and exception handling
  • Object-oriented programming in Python
  • Python namespaces and scopes
  • Python time and date

ShowMeAI series tutorials recommended

  • Illustrated Python programming: From beginner to Master series of tutorials
  • Illustrated Data Analysis: From beginner to master series of tutorials
  • The mathematical Basics of AI: From beginner to Master series of tutorials
  • Illustrated Big Data Technology: From beginner to master