Public account: You and the cabin by: Peter Editor: Peter
Hello, I’m Peter
Peter introduced the Time module in detail in his previous Python time series article, and this article focuses on the DateTime module.
This module is an upgraded version of the Time module, with more common and comprehensive usage. Various examples will be provided to illustrate the use of this module.
Small talk
Recently, a lawyer added Peter through the public account. He learned Python in his spare time. Is this society really such a roll?
Friends, when it comes to Python, the best way to learn Python is to follow the example of Urhut
directory
Table of contents for reference:
Pandas articles
Pandas has been updated to article 26, with a recent focus on how to handle time series related data in Python or Pandas.
The last article is: Time module explanation, please refer to:
Datetime module
The main class
The main classes contained in the Datetime module are:
- Date: a date object. The commonly used attributes are year, month, and day
- Time: A time object. The main properties are hour, minute, second, and microsecond
- Datetime: a combination of date and datetime objects
- Datetime_CAPI: C interface for date objects
- Timedelta: Time interval between two times
- Tzinfo: Abstract base class for the time zone information object
constant
There are two constants:
- MAXYEAR: Returns the maximum year that can be represented, datetime.MAXYEAR
- MINYEAR: Returns the smallest year that can be represented, datetime.minyear
Five categories:
The following describes the specific use methods of the five categories in the Datetime module:
- date
- time
- datetime
- timedelta
- tzinfo
We must import the module before we can use it
from datetime import * # * denotes all classes below the module
Copy the code
The date class
Date object consists of year, year, month, and day.
The current time
Way # 1
from datetime import date
datetime.today().date()
Copy the code
datetime.date(2021, 10, 20)
Copy the code
Way # 2
from datetime import date
# today is a date object that returns the current date
today = date.today()
today
Copy the code
datetime.date(2021, 10, 20)
Copy the code
Accessed by year, month, and day property descriptors:
print("This year:",today.year) # return the year of the today object
print("This month:",today.month) # return the month of the today object
print("Today:",today.day) # return the day of the today object
Copy the code
This year: 2021 This month: 10 Today: 20Copy the code
Through the.__getattribute__ (…). Method to obtain the above values:
today.__getattribute__("year")
Copy the code
2021
Copy the code
today.__getattribute__("month")
Copy the code
10
Copy the code
today.__getattribute__("day")
Copy the code
20
Copy the code
In addition, we can also access information about other date classes:
print("Current date:",today) # current date
print("Current date (string) :",today.ctime()) # return a string of dates
print("Time (tuple) :",today.timetuple()) Time tuple information for the current date
Copy the code
Current Date: 2021-10-20 Current date (string format) : Wed Oct 20 00:00:00 2021 time (tuple format) : 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)Copy the code
print("This week:",today.weekday()) # 0 stands for Monday, and so on
print("Ordinal number of Gregorian calendar:",today.toordinal()) # return the ordinal number of the Gregorian calendar date
print(Year/week/week:,today.isocalendar()) # return a tuple: week of the year, day of the week
Copy the code
Calendar Ordinal: 738083 years/Weeks/weeks: (2021, 42, 3)Copy the code
Custom time
Specify an arbitrary time:
# Customize a time
new_date = date(2021.12.8)
new_date
Copy the code
datetime.date(2021, 12, 8)
Copy the code
# return different attributes
print("year: ", new_date.year)
print("month: ", new_date.month)
print("day: ", new_date.day)
Copy the code
year: 2021
month: 12
day: 8
Copy the code
# return time tuple
new_date.timetuple()
Copy the code
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)
Copy the code
# return the Gregorian ordinal number
new_date.toordinal()
Copy the code
738132
Copy the code
# return week, 0 = 1,1 = 2
new_date.weekday()
Copy the code
2
Copy the code
# return week, 1 represents Monday, 1 represents Tuesday
new_date.isoweekday()
Copy the code
3
Copy the code
# return tuple :(year, week, day)
new_date.isocalendar()
Copy the code
(2021, 49, 3)
Copy the code
# Return date as a string in ISO 8601 format 'YYYY-MM-DD'
new_date.isoformat()
Copy the code
'2021-12-08'
Copy the code
# return a string of dates
new_date.ctime()
Copy the code
'Wed Dec 8 00:00:00 2021'
Copy the code
Specify different date output formats:
# returns a date string in the specified format
new_date.strftime("%Y-%m-%d")
Copy the code
'2021-12-08'
Copy the code
new_date.strftime("%Y/%m/%d")
Copy the code
'2021/12/08'
Copy the code
new_date.strftime("%Y %m %d")
Copy the code
'08 December 2021'Copy the code
# replace time, for example we replace new_date
r_date = new_date.replace(2021.11.10)
r_date
Copy the code
datetime.date(2021, 11, 10)
Copy the code
In this case, we generate a new date object, and of course we can display the specified parameters:
new_date.replace(year=2021,month=11,day=11)
Copy the code
datetime.date(2021, 11, 11)
Copy the code
Gregorian calendar ordinal correlation
The ordinal is related to the toordinal method
# check the ordinal number of the current date
to_timestamp = today.toordinal()
to_timestamp
Copy the code
738083
Copy the code
Converts the given ordinal to a specific date and time: fromordinal
print(date.fromordinal(to_timestamp))
Copy the code
2021-10-20
Copy the code
Timestamp conversion
The conversion is done using the function fromtimestamp
import time
t = time.time() The timestamp of the current time
t
Copy the code
1634732660.382036
Copy the code
print(date.fromtimestamp(t)) # timestamp --> date
Copy the code
2021-10-20
Copy the code
Convert arbitrary timestamps:
date.fromtimestamp(1698382719)
Copy the code
datetime.date(2023, 10, 27)
Copy the code
Time formatting
Let's format the output of the Today object
today
Copy the code
datetime.date(2021, 10, 20)
Copy the code
print(today.strftime("%Y/%m/%d"))
Copy the code
2021/10/20
Copy the code
print(today.strftime("%Y-%m-%d"))
Copy the code
2021-10-20
Copy the code
Time class
Create an object
Start by creating an arbitrary time
from datetime import time
t = time(20.30.40.1000)
Copy the code
Accessing common properties
Hours, minutes and seconds are common attributes
print(t.hour) When #
print(t.minute) # points
print(t.second) # s
print(t.microsecond) # microseconds
Copy the code
20, 30, 40, 1000Copy the code
Formatted output
# return time string in ISO 8601 format
t.isoformat()
Copy the code
'20:30:40. 001000'Copy the code
# specify the format of the output
t.strftime("%H:%M:%S:%f")
Copy the code
'20:30:40:001000'
Copy the code
Also, there is a replacement function:
# implicit substitution
t.replace(14.37.8)
Copy the code
datetime.time(14, 37, 8, 1000)
Copy the code
# explicit substitution
t.replace(hour=4,minute=18,second=19)
Copy the code
datetime.time(4, 18, 19, 1000)
Copy the code
Datetime class
A datetime object contains all information about a Date object and a time object. Summary of datetime-specific methods and attributes:
- The date (…). : Returns the date portion of a Datetime object
- Time (…). : Returns the time portion of a DateTime object
- Utctimetuple (…). : Returns the UTC time tuple part
Generate current date
from datetime import datetime
k = datetime.today() # Specify the current time
print(k)
Copy the code
The 2021-10-20 20:24:23. 053493Copy the code
Access different attribute information for the current time:
print("year:",k.year)
print("month:",k.month)
print("day:",k.day)
Copy the code
year: 2021
month: 10
day: 20
Copy the code
Generate current time
# return the current time
n = datetime.now()
n
Copy the code
datetime.datetime(2021, 10, 20, 20, 24, 23, 694127)
Copy the code
Return the date portion of the datetime object
n.date()
Copy the code
datetime.date(2021, 10, 20)
Copy the code
Return the time portion of the dateTime object
n.time()
Copy the code
datetime.time(20, 24, 23, 694127)
Copy the code
Return the UTC tuple portion of the datetime object
n.utctimetuple()
Copy the code
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)
Copy the code
Additional attribute information can also be generated:
# Return a datetime object for the current UTC date and time
print(datetime.utcnow())
Copy the code
The 2021-10-20 12:24:24. 241577Copy the code
# Datetime object for the given timestamp
print(datetime.fromtimestamp(1697302830))
Copy the code
The 2023-10-15 01:00:30Copy the code
Datetime object that specifies the ordinal number of the Gregorian calendar
print(datetime.fromordinal(738000))Copy the code
2021-07-29 00:00:00
Copy the code
# Concatenate date and time
print(datetime.combine(date(2020.12.25), time(11.22.54)))
Copy the code
The 2020-12-25 11:22:54Copy the code
Specify any time
# specify an arbitrary time
d = datetime(2021.9.25.11.24.23)
Copy the code
print(d.date()) # date
print(d.time()) # time
print(d.timetz()) Split the time zone attribute from datetime
print(d.timetuple()) # time tuple
print(d.toordinal()) # Same as date.toordinal
print(d.weekday()) # Two weeks
print(d.isoweekday())
print(d.isocalendar()) ISO format output
print(d.isoformat())
print(d.strftime("%Y-%m-%d %H:%M:%S")) # specify format
print(d.replace(year=2021,month=1)) # replace
Copy the code
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
Copy the code
Formatted output
# Direct formatted output for time
print(datetime.strptime("2020-12-25"."%Y-%m-%d"))
Copy the code
2020-12-25 00:00:00
Copy the code
Formatted output for a given Datetime object, such as the instantiated object k created above:
k
Copy the code
datetime.datetime(2021, 10, 20, 20, 24, 23, 53493)
Copy the code
# format output
k.strftime("%Y-%m-%d %H:%M:%S")
Copy the code
'the 2021-10-20 20:24:23'Copy the code
Timedelta class
The timedelta object represents a time period, the difference between two dates or datetimes.
Currently, the following parameters are supported :weeks, days, hours, minutes, seconds, milliseconds, and microseconds.
The current date
from datetime import timedelta, date, datetime
d = date.today() # current date
d
Copy the code
datetime.date(2021, 10, 20)
Copy the code
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
Copy the code
Today: 2021-10-20 plus 5 days: 2021-10-25 plus 3 days +8 hours: 2021-10-23Copy the code
Current point in time
# current point in time
now = datetime.now()
now
Copy the code
datetime.datetime(2021, 10, 20, 20, 24, 26, 777335)
Copy the code
print(now + timedelta(hours=4)) # plus 4 hours
print(now + timedelta(weeks=2)) # plus 2 weeks
print(now - timedelta(seconds=500)) Minus 500 seconds
Copy the code
2021-10-21 00:24:26.777335
2021-11-03 20:24:26.777335
2021-10-20 20:16:06.777335
Copy the code
Datetime object difference
delta = datetime(2020.12.26) - datetime(2020.12.12.20.12)
print(delta)
Copy the code
13 days, 3:48:00
Copy the code
delta.days # Date interval: days
Copy the code
13
Copy the code
delta.seconds # Date interval: seconds
Copy the code
13680
Copy the code
delta.total_seconds() # # Convert all to seconds
Copy the code
1136880.0
Copy the code
Two date differences
d1 = datetime(2021.10.1)
d2 = datetime(2021.10.8)
Copy the code
d1.__sub__(d2) # d1 - d2
Copy the code
datetime.timedelta(days=-7)
Copy the code
d2.__sub__(d1) # d2 - d1
Copy the code
datetime.timedelta(days=7)
Copy the code
# rsub means d2-d1
d1.__rsub__(d2)
Copy the code
datetime.timedelta(days=7)
Copy the code
The difference between the two dates above results in datetime.timedelta. If the result is an integer, do as follows:
d1.__sub__(d2).days
Copy the code
7 -Copy the code
Tzinfo classes
The time zone is specified
Specify the time zone
from datetime import date, timedelta, datetime, timezone
tz_utc_8 = timezone(timedelta(hours=8)) # create time zone
print(tz_utc_8)
Copy the code
UTC+08:00
Copy the code
now = datetime.now()
print(now)
Copy the code
The 2021-10-20 20:24:28. 844732Copy the code
new_time = now.replace(tzinfo=tz_utc_8) # Force plus 8 hours
print(new_time)
Copy the code
The 2021-10-20 20:24:28. 844732 + 08:00Copy the code
Switching time zones
Get the UTC time
utc_now = datetime.utcnow().replace(tzinfo=timezone.utc) # specify utc time zone
print(utc_now)
Copy the code
The 2021-10-20 12:24:29. 336367 + 00:00Copy the code
# Switch to east 8 via astimeZone
beijing = utc_now.astimezone(timezone(timedelta(hours=8)))
print(beijing)
Copy the code
The 2021-10-20 20:24:29. 336367 + 08:00Copy the code
Change the UTC time zone to East 9: Tokyo time
tokyo = utc_now.astimezone(timezone(timedelta(hours=9)))
print(tokyo)
Copy the code
The 2021-10-20 21:24:29. 336367 + 09:00Copy the code
# Switch from Beijing time to Tokyo Time
tokyo_new = beijing.astimezone(timezone(timedelta(hours=9)))
print(tokyo_new)
Copy the code
The 2021-10-20 21:24:29. 336367 + 09:00Copy the code
Common application
The timestamp is converted to a date
import time
now_timestamp = time.time()
now_timestamp
Copy the code
1634732670.286224
Copy the code
# 1- Switch to a specific point in time
now = time.ctime(now_timestamp)
print(now)
Copy the code
Wed Oct 20 20:24:30 2021
Copy the code
# 2- The timestamp is converted to a time tuple before strftime is converted to the specified format
now_tuple = time.localtime(now_timestamp)
print(now_tuple)
Copy the code
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)
Copy the code
time.strftime("%Y/%m/%d %H:%M:%S", now_tuple)
Copy the code
'2021/10/20 20:24:30'
Copy the code
# Select a specific timestamp
timestamp = 1618852721
a = time.localtime(timestamp) Get time tuple form data
print("Time tuple data:",a)
time.strftime("%Y/%m/%d %H:%M:%S", a) # format
Copy the code
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'Copy the code
time.ctime(1618852741)
Copy the code
'Tue Apr 20 01:19:01 2021'
Copy the code
Date time converts to timestamp
Given date data as a string, how do we convert it to the format we want?
date = "The 2021-10-26 11:45:34"
# 1. The time string is converted to the time array
date_array = time.strptime(date, "%Y-%m-%d %H:%M:%S")
date_array
Copy the code
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)
Copy the code
# 2, Check the time array data
print("Time array:", date_array)
Copy the code
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)Copy the code
# 3, mktime time array converted to timestamp
time.mktime(date_array)
Copy the code
1635219934.0
Copy the code
Date formatting
import time
old = "The 2021-09-12 12:28:45"
# 1. Convert to a 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 the display format
print("Original format time:",old)
print("New format time:",new)
Copy the code
Original format time: 2021-09-12 12:28:45 New format time: 2021/09/12 12-28-45Copy the code