Official account: Special House
Author: Peter
Editor: Peter
Hello, I'm Peter~
In the previous Python time series article, Peter introduced the time module in detail. This article focuses on the datetime module.
This module can be said to be an upgraded version of the time module. The usage is more common and comprehensive. The article will explain the use of this module through various examples.
gossip
Recently, a lawyer has added Peter to the official account. He has studied Python after work. Is this really such a society?
Friends, it's best to learn Python from youer hut~
catalogue
Table of contents reference:
Pandas article
Pandas related articles have been updated to Article 26. The recent focus is how to process time series related data in Python or pandas.
The last article was about the time module. Please refer to:
datetime module
Main category
The main classes contained in the datetime module are:
- date: date object. Common attributes include year, month, day, etc
- Time: time object. The main attributes are hour, minute, second and microsecond
- Datetime: date time object, combination of attribute date and attribute datetime
- datetime_CAPI: C language interface of date object
- timedelta: the time interval between two times
- tzinfo: abstract base class of time zone information object
constant
There are mainly two constants:
- Maxear: returns the maximum year that can be represented, datetime.maxear
- MINYEAR: returns the smallest year that can be represented, datetime.MINYEAR
5 categories
The following describes the specific usage of the five categories in the datetime module:
- date
- time
- datetime
- timedelta
- tzinfo
We must import the module before we use it
from datetime import * # *Represents all classes under the module
date class
The date object consists of year, month and day:
current time
# Mode 1 from datetime import date datetime.today().date()
datetime.date(2021, 10, 20)
# Mode 2 from datetime import date # today is a date object that returns the current date today = date.today() today
datetime.date(2021, 10, 20)
Access through three attribute descriptors: year, month and day:
print("this year:",today.year) # Returns the year of the today object print("This month:",today.month) # Returns the month of the today object print("Today:",today.day) # Returns the day of the today object
This year: 2021 Current month: 10 Today: 20
Pass__ getattribute__ (...) method to obtain the above value:
today.__getattribute__("year")
2021
today.__getattribute__("month")
10
today.__getattribute__("day")
20
In addition, we can also access the information of other date classes:
print("Current date:",today) # current date print("current date(String form): ",today.ctime()) # Returns a string of dates print("time(Tuple form): ",today.timetuple()) # Time tuple information of the current date
Current date: 2021-10-20 current date(String form): Wed Oct 20 00:00:00 2021 time(Tuple form): time.struct_time(tm_year=2021, tm_mon=10, tm_mday=20, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=293, tm_isdst=-1)
print("This week:",today.weekday()) # 0 stands for Monday, and so on print("Gregorian ordinal number:",today.toordinal()) # Returns the ordinal number of the Gregorian calendar date print("year/Number of weeks/Week:",today.isocalendar()) # Returns a tuple: the week of the year and the day of the week
This week: 2 Gregorian calendar ordinal number: 738083 year/Number of weeks/Week: (2021, 42, 3)
Custom time
Specify an arbitrary time:
# Customize a time new_date = date(2021,12,8) new_date
datetime.date(2021, 12, 8)
# Return different properties print("year: ", new_date.year) print("month: ", new_date.month) print("day: ", new_date.day)
year: 2021 month: 12 day: 8
# Return time tuple new_date.timetuple()
time.struct_time(tm_year=2021, tm_mon=12, tm_mday=8, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=342, tm_isdst=-1)
# Returns the Gregorian ordinal number new_date.toordinal()
738132
# Returns the week, 0 for Monday and 1 for Tuesday new_date.weekday()
2
# Return week, 1 for Monday and 2 for Tuesday new_date.isoweekday()
3
# Return tuple: (year, week, day of week) new_date.isocalendar()
(2021, 49, 3)
# Returns the string form of date in ISO 8601 format 'YYYY-MM-DD' new_date.isoformat()
'2021-12-08'
# Returns a string of dates new_date.ctime()
'Wed Dec 8 00:00:00 2021'
Specify a different date output format:
# Returns a date string in the specified format new_date.strftime("%Y-%m-%d")
'2021-12-08'
new_date.strftime("%Y/%m/%d")
'2021/12/08'
new_date.strftime("%Y year%m month%d day")
'2021 December 8'
# Replacement time, for example, we replace new_date r_date = new_date.replace(2021,11,10) r_date
datetime.date(2021, 11, 10)
In this case, we generate a new date object. Of course, we can also display the specified parameters:
new_date.replace(year=2021,month=11,day=11)
datetime.date(2021, 11, 11)
Gregorian ordinal correlation
The Gregorian ordinal number is related to the toolbar method
# View the Gregorian ordinal number of the current date to_timestamp = today.toordinal() to_timestamp
738083
Convert the given Gregorian ordinal number to a specific time and date: from ordinal
print(date.fromordinal(to_timestamp))
2021-10-20
Timestamp conversion
Convert through the function fromtimestamp
import time t = time.time() # Timestamp of the current time t
1634732660.382036
print(date.fromtimestamp(t)) # Timestamp -- > date
2021-10-20
Convert arbitrary timestamp:
date.fromtimestamp(1698382719)
datetime.date(2023, 10, 27)
Time formatting
# Let's format and output the today object today
datetime.date(2021, 10, 20)
print(today.strftime("%Y/%m/%d"))
2021/10/20
print(today.strftime("%Y-%m-%d"))
2021-10-20
time class
create object
Create an arbitrary time first
from datetime import time t = time(20,30,40,1000)
Access common properties
Hours, minutes and seconds are common attributes
print(t.hour) # Time print(t.minute) # branch print(t.second) # second print(t.microsecond) # Microsecond
20 30 40 1000
Format output
# Returns a time string in ISO 8601 format t.isoformat()
'20:30:40.001000'
# Specifies the format of the output t.strftime("%H:%M:%S:%f")
'20:30:40:001000'
Similarly, it also has the replacement function:
# Implicit substitution t.replace(14,37,8)
datetime.time(14, 37, 8, 1000)
# Explicit substitution t.replace(hour=4,minute=18,second=19)
datetime.time(4, 18, 19, 1000)
datetime class
The datetime object contains all the information of the date object and the time object. Summary of methods and properties specific to datetime:
- date(...): returns the date part of the datetime object
- time(...): returns the time part of the datetime object
- Utctimetaple (...): returns the UTC time tuple part
Generate current date
from datetime import datetime k = datetime.today() # Current specific time print(k)
2021-10-20 20:24:23.053493
Access different attribute information of the current time:
print("year:",k.year) print("month:",k.month) print("day:",k.day)
year: 2021 month: 10 day: 20
Generate current time
# Returns the current specific time n = datetime.now() n
datetime.datetime(2021, 10, 20, 20, 24, 23, 694127)
# Returns the date part of the datetime object n.date()
datetime.date(2021, 10, 20)
# Returns the time portion of the datetime object n.time()
datetime.time(20, 24, 23, 694127)
# Returns the UTC time tuple portion of the datetime object n.utctimetuple()
time.struct_time(tm_year=2021, tm_mon=10, tm_mday=20, tm_hour=20, tm_min=24, tm_sec=23, tm_wday=2, tm_yday=293, tm_isdst=0)
Other attribute information can also be generated:
# Returns the datetime object of the current UTC date and time print(datetime.utcnow())
2021-10-20 12:24:24.241577
# datetime object for the given timestamp print(datetime.fromtimestamp(1697302830))
2023-10-15 01:00:30
# datetime object that specifies the Gregorian ordinal number print(datetime.fromordinal(738000) )
2021-07-29 00:00:00
# Splicing date and time print(datetime.combine(date(2020,12,25), time(11,22,54)))
2020-12-25 11:22:54
Specify any time
# Specify an arbitrary time d = datetime(2021,9,25,11,24,23)
print(d.date()) # date print(d.time()) # time print(d.timetz()) # Split the time of the specific time zone attribute from datetime print(d.timetuple()) # time tuples print(d.toordinal()) # Same as date.toolbar print(d.weekday()) # Two weeks print(d.isoweekday()) print(d.isocalendar()) # ISO formatted output print(d.isoformat()) print(d.strftime("%Y-%m-%d %H:%M:%S")) # Specify format print(d.replace(year=2021,month=1)) # replace
2021-09-25 11:24:23 11:24:23 time.struct_time(tm_year=2021, tm_mon=9, tm_mday=25, tm_hour=11, tm_min=24, tm_sec=23, tm_wday=5, tm_yday=268, tm_isdst=-1) 738058 5 6 (2021, 38, 6) 2021-09-25T11:24:23 2021-09-25 11:24:23 2021-01-25 11:24:23
Format output
# Direct formatted output of time print(datetime.strptime("2020-12-25","%Y-%m-%d"))
2020-12-25 00:00:00
The formatted output of a given datetime object, such as the instantiated object k created above:
k
datetime.datetime(2021, 10, 20, 20, 24, 23, 53493)
# Format output k.strftime("%Y-%m-%d %H:%M:%S")
'2021-10-20 20:24:23'
timedelta class
The timedelta object represents a time period, that is, the difference between two dates or datetime.
Currently supported parameters: weeks, days, hours, minutes, seconds, milliseconds, microseconds.
current date
from datetime import timedelta, date, datetime d = date.today() # current date d
datetime.date(2021, 10, 20)
print("today:",d) print("Plus 5 days:",d + timedelta(days=5)) # Plus 5 days print("Plus 3 days+8 Hours:", d + timedelta(days=3,hours=8)) # Plus 3 days and 8 hours
Today: 2021-10-20 Plus 5 days: 2021-10-25 Plus 3 days+8 Hours: 2021-10-23
Current time point
# Current time point now = datetime.now() now
datetime.datetime(2021, 10, 20, 20, 24, 26, 777335)
print(now + timedelta(hours=4)) # Plus 4 hours print(now + timedelta(weeks=2)) # Plus 2 weeks print(now - timedelta(seconds=500)) # Minus 500 seconds
2021-10-21 00:24:26.777335 2021-11-03 20:24:26.777335 2021-10-20 20:16:06.777335
datetime object difference
delta = datetime(2020,12,26) - datetime(2020,12,12,20,12) print(delta)
13 days, 3:48:00
delta.days # Date interval: days
13
delta.seconds # Date interval: seconds
13680
delta.total_seconds() # # Convert all to seconds
1136880.0
Difference between two dates
d1 = datetime(2021,10,1) d2 = datetime(2021,10,8)
d1.__sub__(d2) # d1 - d2
datetime.timedelta(days=-7)
d2.__sub__(d1) # d2 - d1
datetime.timedelta(days=7)
# rsub denotes d2 - d1 d1.__rsub__(d2)
datetime.timedelta(days=7)
The result of the difference between the above two dates is datetime.timedelta. If the result of integer type is obtained, operate as follows:
d1.__sub__(d2).days
-7
tzinfo class
The main function is to specify the time zone where the time is located
Specify time zone
from datetime import date, timedelta, datetime, timezone tz_utc_8 = timezone(timedelta(hours=8)) # Create time zone print(tz_utc_8)
UTC+08:00
now = datetime.now() print(now)
2021-10-20 20:24:28.844732
new_time = now.replace(tzinfo=tz_utc_8) # Mandatory plus 8 hours print(new_time)
2021-10-20 20:24:28.844732+08:00
Time zone switching
# Get UTC time utc_now = datetime.utcnow().replace(tzinfo=timezone.utc) # Specify utc time zone print(utc_now)
2021-10-20 12:24:29.336367+00:00
# Switch to East Zone 8 through astimezone beijing = utc_now.astimezone(timezone(timedelta(hours=8))) print(beijing)
2021-10-20 20:24:29.336367+08:00
# Switch UTC time zone to Dongjiu District: Tokyo time tokyo = utc_now.astimezone(timezone(timedelta(hours=9))) print(tokyo)
2021-10-20 21:24:29.336367+09:00
# Directly switch from Beijing time (East 8th District) to Tokyo time (East 9th District) tokyo_new = beijing.astimezone(timezone(timedelta(hours=9))) print(tokyo_new)
2021-10-20 21:24:29.336367+09:00
Common applications
Timestamp to date
import time now_timestamp = time.time() now_timestamp
1634732670.286224
# 1 - convert to specific time point now = time.ctime(now_timestamp) print(now)
Wed Oct 20 20:24:30 2021
# 2 - timestamp is converted to time tuple first, and strftime is converted to the specified format now_tuple = time.localtime(now_timestamp) print(now_tuple)
time.struct_time(tm_year=2021, tm_mon=10, tm_mday=20, tm_hour=20, tm_min=24, tm_sec=30, tm_wday=2, tm_yday=293, tm_isdst=0)
time.strftime("%Y/%m/%d %H:%M:%S", now_tuple)
'2021/10/20 20:24:30'
# Select a specific timestamp timestamp = 1618852721 a = time.localtime(timestamp) # Get time tuple data print("Time tuple data:",a) time.strftime("%Y/%m/%d %H:%M:%S", a) # format
Time tuple data: time.struct_time(tm_year=2021, tm_mon=4, tm_mday=20, tm_hour=1, tm_min=18, tm_sec=41, tm_wday=1, tm_yday=110, tm_isdst=0) '2021/04/20 01:18:41'
time.ctime(1618852741)
'Tue Apr 20 01:19:01 2021'
Date time to timestamp
Given a string type of date data, how to convert it into the time format we want?
date = "2021-10-26 11:45:34" # 1. Convert time string to time array date_array = time.strptime(date, "%Y-%m-%d %H:%M:%S") date_array
time.struct_time(tm_year=2021, tm_mon=10, tm_mday=26, tm_hour=11, tm_min=45, tm_sec=34, tm_wday=1, tm_yday=299, tm_isdst=-1)
# 2. View time array data print("Time array:", date_array)
Time array: time.struct_time(tm_year=2021, tm_mon=10, tm_mday=26, tm_hour=11, tm_min=45, tm_sec=34, tm_wday=1, tm_yday=299, tm_isdst=-1)
# 3. Convert mktime array to timestamp time.mktime(date_array)
1635219934.0
Date formatting
import time old = "2021-09-12 12:28:45" # 1. Convert to time array time_array = time.strptime(old, "%Y-%m-%d %H:%M:%S") # 2. Convert to new time format (2021 / 09 / 12 12-28-45) new = time.strftime("%Y/%m/%d %H-%M-%S",time_array) # Specify display format print("Original format time:",old) print("New format time:",new)
Original format time: 2021-09-12 12:28:45 New format time: 2021/09/12 12-28-45