Python日期时间模块
在Python中,日期和时间不是它们自己的数据类型,但是可以导入一个名为datetime的模块来处理日期和时间。 Python Datetime 模块内置于Python中,因此无需在外部安装。
Python Datetime 模块提供了处理日期和时间的类。这些类提供了许多处理日期、时间和时间间隔的函数。 Date 和 datetime 是Python中的一个对象,因此当您操作它们时,您实际上是在操作对象,而不是字符串或时间戳。
DateTime 模块分为 6 个主要类 -
- date – 一个理想化的朴素日期,假设当前的公历一直有效,并且永远有效。它的属性是年、月和日。
- time – 一个理想化的时间,独立于任何特定的一天,假设每天正好有 24*60*60 秒。它的属性是小时、分钟、秒、微秒和tzinfo。
- datetime – 它是日期和时间以及属性年、月、日、小时、分钟、秒、微秒和 tzinfo 的组合。
- timedelta – 表示两个日期、时间或日期时间实例之间的差异的持续时间,以微秒为单位。
- tzinfo - 它提供时区信息对象。
- timezone – 将 tzinfo 抽象基类实现为与 UTC 的固定偏移量的类(3.2 版中的新功能)。
日期类
日期类用于在Python中实例化日期对象。实例化此类的对象时,它表示格式为 YYYY-MM-DD 的日期。此类的构造函数需要三个强制参数年、月和日期。
构造函数语法:
class datetime.date(year, month, day)
参数必须在以下范围内 -
- MINYEAR <= 年 <= MAXYEAR
- 1 <= 月 <= 12
- 1 <= 天 <= 给定月份和年份的天数
注意– 如果参数不是整数,则会引发 TypeError,如果超出范围,则会引发 ValueError。
示例 1:在Python中表示日期的 Date 对象
Python3
# Python program to
# demonstrate date class
# import the date class
from datetime import date
# initializing constructor
# and passing arguments in the
# format year, month, date
my_date = date(1996, 12, 11)
print("Date passed as argument is", my_date)
# Uncommenting my_date = date(1996, 12, 39)
# will raise an ValueError as it is
# outside range
# uncommenting my_date = date('1996', 12, 11)
# will raise a TypeError as a string is
# passed instead of integer
Python3
# Python program to
# print current date
from datetime import date
# calling the today
# function of date class
today = date.today()
print("Today's date is", today)
Python3
from datetime import date
# date object of today's date
today = date.today()
print("Current year:", today.year)
print("Current month:", today.month)
print("Current day:", today.day)
Python3
from datetime import datetime
# Getting Datetime from timestamp
date_time = datetime.fromtimestamp(1887639468)
print("Datetime from timestamp:", date_time)
Python3
from datetime import date
# calling the today
# function of date class
today = date.today()
# Converting the date to the string
Str = date.isoformat(today)
print("String Representation", Str)
print(type(Str))
Python3
# Python program to
# demonstrate time class
from datetime import time
# calling the constructor
my_time = time(13, 24, 56)
print("Entered time", my_time)
# calling constructor with 1
# argument
my_time = time(minute=12)
print("\nTime with one argument", my_time)
# Calling constructor with
# 0 argument
my_time = time()
print("\nTime without argument", my_time)
# Uncommenting time(hour = 26)
# will rase an ValueError as
# it is out of range
# uncommenting time(hour ='23')
# will raise TypeError as
# string is passed instead of int
Python3
from datetime import time
Time = time(11, 34, 56)
print("hour =", Time.hour)
print("minute =", Time.minute)
print("second =", Time.second)
print("microsecond =", Time.microsecond)
Python3
from datetime import time
# Creating Time object
Time = time(12,24,36,1212)
# Converting Time object to string
Str = Time.isoformat()
print("String Representation:", Str)
print(type(Str))
Python3
# Python program to
# demonstrate datetime object
from datetime import datetime
# Initializing constructor
a = datetime(1999, 12, 12)
print(a)
# Initializing constructor
# with time parameters as well
a = datetime(1999, 12, 12, 12, 12, 12, 342380)
print(a)
Python3
from datetime import datetime
a = datetime(1999, 12, 12, 12, 12, 12)
print("year =", a.year)
print("month =", a.month)
print("hour =", a.hour)
print("minute =", a.minute)
print("timestamp =", a.timestamp())
Python3
from datetime import datetime
# Calling now() function
today = datetime.now()
print("Current date and time is", today)
Python3
from datetime import datetime as dt
# Getting current date and time
now = dt.now()
string = dt.isoformat(now)
print(string)
print(type(string))
Python3
# Timedelta function demonstration
from datetime import datetime, timedelta
# Using current time
ini_time_for_now = datetime.now()
# printing initial_date
print("initial_date", str(ini_time_for_now))
# Calculating future dates
# for two years
future_date_after_2yrs = ini_time_for_now + timedelta(days=730)
future_date_after_2days = ini_time_for_now + timedelta(days=2)
# printing calculated future_dates
print('future_date_after_2yrs:', str(future_date_after_2yrs))
print('future_date_after_2days:', str(future_date_after_2days))
Python3
# Timedelta function demonstration
from datetime import datetime, timedelta
# Using current time
ini_time_for_now = datetime.now()
# printing initial_date
print("initial_date", str(ini_time_for_now))
# Some another datetime
new_final_time = ini_time_for_now + \
timedelta(days=2)
# printing new final_date
print("new_final_time", str(new_final_time))
# printing calculated past_dates
print('Time difference:', str(new_final_time -
ini_time_for_now))
Python3
# Python program to demonstrate
# strftime() function
from datetime import datetime as dt
# Getting current date and time
now = dt.now()
print("Without formatting", now)
# Example 1
s = now.strftime("%A %m %-Y")
print('\nExample 1:', s)
# Example 2
s = now.strftime("%a %-m %y")
print('\nExample 2:', s)
# Example 3
s = now.strftime("%-I %p %S")
print('\nExample 3:', s)
# Example 4
s = now.strftime("%H:%M:%S")
print('\nExample 4:', s)
Python3
# import datetime module from datetime
from datetime import datetime
# consider the time stamps from a list in string
# format DD/MM/YY H:M:S.micros
time_data = ["25/05/99 02:35:8.023", "26/05/99 12:45:0.003",
"27/05/99 07:35:5.523", "28/05/99 05:15:55.523"]
# format the string in the given format : day/month/year
# hours/minutes/seconds-micro seconds
format_data = "%d/%m/%y %H:%M:%S.%f"
# Using strptime with datetime we will format string
# into datetime
for i in time_data:
print(datetime.strptime(i, format_data))
Python3
from datetime import datetime
from pytz import timezone
format = "%Y-%m-%d %H:%M:%S %Z%z"
# Current time in UTC
now_utc = datetime.now(timezone('UTC'))
print(now_utc.strftime(format))
timezones = ['Asia/Kolkata', 'Europe/Kiev', 'America/New_York']
for tzone in timezones:
# Convert to Asia/Kolkata time zone
now_asia = now_utc.astimezone(timezone(tzone))
print(now_asia.strftime(format))
输出:
Date passed as argument is 1996-12-11
Traceback (most recent call last):
File "/home/ccabfb570d9bd1dcd11dc4fe55fd6ba2.py", line 14, in
my_date = date(1996, 12, 39)
ValueError: day is out of range for month
Traceback (most recent call last):
File "/home/53b974e10651f1853eee3c004b48c481.py", line 18, in
my_date = date('1996', 12, 11)
TypeError: an integer is required (got type str)
示例 2:获取当前日期
使用日期类的今天()函数返回当前本地日期。 today()函数带有几个属性(年、月和日)。这些可以单独打印。
Python3
# Python program to
# print current date
from datetime import date
# calling the today
# function of date class
today = date.today()
print("Today's date is", today)
Today's date is 2021-08-19
示例 3:获取今天的年月日
我们可以使用日期类的年月日属性从日期对象中获取年月日属性。
Python3
from datetime import date
# date object of today's date
today = date.today()
print("Current year:", today.year)
print("Current month:", today.month)
print("Current day:", today.day)
Current year: 2021
Current month: 8
Current day: 19
示例 4:从时间戳获取日期
我们可以使用 fromtimestamp() 方法从时间戳 y=创建日期对象。时间戳是从 1970 年 1 月 1 日 UTC 到特定日期的秒数。
Python3
from datetime import datetime
# Getting Datetime from timestamp
date_time = datetime.fromtimestamp(1887639468)
print("Datetime from timestamp:", date_time)
Datetime from timestamp: 2029-10-25 16:17:48
示例 5:将日期转换为字符串
我们可以使用两个函数 isoformat() 和 strftime() 将日期对象转换为字符串表示。
Python3
from datetime import date
# calling the today
# function of date class
today = date.today()
# Converting the date to the string
Str = date.isoformat(today)
print("String Representation", Str)
print(type(Str))
String Representation 2021-08-19
日期类方法列表
Function Name | Description |
---|---|
ctime() | Return a string representing the date |
fromisocalendar() | Returns a date corresponding to the ISO calendar |
fromisoformat() | Returns a date object from the string representation of the date |
fromordinal() | Returns a date object from the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1 |
fromtimestamp() | Returns a date object from the POSIX timestamp |
isocalendar() | Returns a tuple year, week, and weekday |
isoformat() | Returns the string representation of the date |
isoweekday() | Returns the day of the week as integer where Monday is 1 and Sunday is 7 |
replace() | Changes the value of the date object with the given parameter |
strftime() | Returns a string representation of the date with the given format |
timetuple() | Returns an object of type time.struct_time |
today() | Returns the current local date |
toordinal() | Return the proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1 |
weekday() | Returns the day of the week as integer where Monday is 0 and Sunday is 6 |
时间班
时间类创建代表当地时间的时间对象,独立于任何一天。
构造函数语法:
class datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
所有参数都是可选的。 tzinfo 可以是 None 否则所有属性必须是以下范围内的整数 -
- 0 <= 小时 < 24
- 0 <= 分钟 < 60
- 0 <= 秒 < 60
- 0 <= 微秒 < 1000000
- 折叠 [0, 1]
示例 1:在Python中表示时间的时间对象
Python3
# Python program to
# demonstrate time class
from datetime import time
# calling the constructor
my_time = time(13, 24, 56)
print("Entered time", my_time)
# calling constructor with 1
# argument
my_time = time(minute=12)
print("\nTime with one argument", my_time)
# Calling constructor with
# 0 argument
my_time = time()
print("\nTime without argument", my_time)
# Uncommenting time(hour = 26)
# will rase an ValueError as
# it is out of range
# uncommenting time(hour ='23')
# will raise TypeError as
# string is passed instead of int
输出:
Entered time 13:24:56
Time with one argument 00:12:00
Time without argument 00:00:00
Traceback (most recent call last):
File "/home/95ff83138a1b3e67731e57ec6dddef25.py", line 21, in
print(time(hour=26))
ValueError: hour must be in 0..23
Traceback (most recent call last):
File "/home/fcee9ba5615b0b74fc3ba39ec9a789fd.py", line 21, in
print(time(hour='23'))
TypeError: an integer is required (got type str)
示例 2:获取小时、分钟、秒和微秒
创建时间对象后,也可以单独打印其属性。
Python3
from datetime import time
Time = time(11, 34, 56)
print("hour =", Time.hour)
print("minute =", Time.minute)
print("second =", Time.second)
print("microsecond =", Time.microsecond)
输出:
hour = 11
minute = 34
second = 56
microsecond = 0
示例 3:将 Time 对象转换为字符串
我们可以使用 isoformat() 方法将时间对象转换为字符串。
Python3
from datetime import time
# Creating Time object
Time = time(12,24,36,1212)
# Converting Time object to string
Str = Time.isoformat()
print("String Representation:", Str)
print(type(Str))
String Representation: 12:24:36.001212
时间类方法列表
Function Name | Description |
---|---|
dst() | Returns tzinfo.dst() is tzinfo is not None |
fromisoformat() | Returns a time object from the string representation of the time |
isoformat() | Returns the string representation of time from the time object |
replace() | Changes the value of the time object with the given parameter |
strftime() | Returns a string representation of the time with the given format |
tzname() | Returns tzinfo.tzname() is tzinfo is not None |
utcoffset() | Returns tzinfo.utcffsets() is tzinfo is not None |
日期时间类
DateTime 类包含有关日期和时间的信息。与日期对象一样,日期时间假定当前的公历在两个方向上扩展;与时间对象一样,datetime 假定每天正好有 3600*24 秒。
构造函数语法:
class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
年、月和日参数是强制性的。 tzinfo 可以是 None,其余所有属性必须是以下范围内的整数 -
- MINYEAR <= 年 <= MAXYEAR
- 1 <= 月 <= 12
- 1 <= 天 <= 给定月份和年份的天数
- 0 <= 小时 < 24
- 0 <= 分钟 < 60
- 0 <= 秒 < 60
- 0 <= 微秒 < 1000000
- 折叠 [0, 1]
注意– 传递整数以外的参数将引发 TypeError,传递超出范围的参数将引发 ValueError。
示例 1:在Python中表示 DateTime 的 DateTime 对象
Python3
# Python program to
# demonstrate datetime object
from datetime import datetime
# Initializing constructor
a = datetime(1999, 12, 12)
print(a)
# Initializing constructor
# with time parameters as well
a = datetime(1999, 12, 12, 12, 12, 12, 342380)
print(a)
输出:
1999-12-12 00:00:00
1999-12-12 12:12:12.342380
示例 2:获取年、月、小时、分钟和时间戳
创建 DateTime 对象后,也可以单独打印其属性。
Python3
from datetime import datetime
a = datetime(1999, 12, 12, 12, 12, 12)
print("year =", a.year)
print("month =", a.month)
print("hour =", a.hour)
print("minute =", a.minute)
print("timestamp =", a.timestamp())
输出:
year = 1999
month = 12
hour = 12
minute = 12
timestamp = 945000732.0
示例 3:当前日期和时间
您可以使用 Datetime.now()函数打印当前日期和时间。 now()函数返回当前的本地日期和时间。
Python3
from datetime import datetime
# Calling now() function
today = datetime.now()
print("Current date and time is", today)
输出:
Current date and time is 2019-10-25 11:12:11.289834
示例 4:将Python日期时间转换为字符串
我们可以使用 datetime.strftime 和 datetime.isoformat 方法在Python中将 Datetime 转换为字符串。
Python3
from datetime import datetime as dt
# Getting current date and time
now = dt.now()
string = dt.isoformat(now)
print(string)
print(type(string))
2021-08-19T18:13:25.346259
日期时间类方法列表
Function Name | Description |
---|---|
astimezone() | Returns the DateTime object containing timezone information. |
combine() | Combines the date and time objects and return a DateTime object |
ctime() | Returns a string representation of date and time |
date() | Return the Date class object |
fromisoformat() | Returns a datetime object from the string representation of the date and time |
fromordinal() | Returns a date object from the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1. The hour, minute, second, and microsecond are 0 |
fromtimestamp() | Return date and time from POSIX timestamp |
isocalendar() | Returns a tuple year, week, and weekday |
isoformat() | Return the string representation of date and time |
isoweekday() | Returns the day of the week as integer where Monday is 1 and Sunday is 7 |
now() | Returns current local date and time with tz parameter |
replace() | Changes the specific attributes of the DateTime object |
strftime() | Returns a string representation of the DateTime object with the given format |
strptime() | Returns a DateTime object corresponding to the date string |
time() | Return the Time class object |
timetuple() | Returns an object of type time.struct_time |
timetz() | Return the Time class object |
today() | Return local DateTime with tzinfo as None |
toordinal() | Return the proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1 |
tzname() | Returns the name of the timezone |
utcfromtimestamp() | Return UTC from POSIX timestamp |
utcoffset() | Returns the UTC offset |
utcnow() | Return current UTC date and time |
weekday() | Returns the day of the week as integer where Monday is 0 and Sunday is 6 |
时间增量类
Python timedelta 类用于计算日期差异,也可用于Python中的日期操作。这是执行日期操作的最简单方法之一。
构造函数语法:
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Returns : Date
示例 1:向 datetime 对象添加天数
Python3
# Timedelta function demonstration
from datetime import datetime, timedelta
# Using current time
ini_time_for_now = datetime.now()
# printing initial_date
print("initial_date", str(ini_time_for_now))
# Calculating future dates
# for two years
future_date_after_2yrs = ini_time_for_now + timedelta(days=730)
future_date_after_2days = ini_time_for_now + timedelta(days=2)
# printing calculated future_dates
print('future_date_after_2yrs:', str(future_date_after_2yrs))
print('future_date_after_2days:', str(future_date_after_2days))
输出:
initial_date 2019-10-25 12:01:01.227848
future_date_after_2yrs: 2021-10-24 12:01:01.227848
future_date_after_2days: 2019-10-27 12:01:01.227848
示例 2:两个日期和时间之间的差异
使用此类也可以找到日期和时间差异。
Python3
# Timedelta function demonstration
from datetime import datetime, timedelta
# Using current time
ini_time_for_now = datetime.now()
# printing initial_date
print("initial_date", str(ini_time_for_now))
# Some another datetime
new_final_time = ini_time_for_now + \
timedelta(days=2)
# printing new final_date
print("new_final_time", str(new_final_time))
# printing calculated past_dates
print('Time difference:', str(new_final_time -
ini_time_for_now))
输出:
initial_date 2019-10-25 12:02:32.799814
new_final_time 2019-10-27 12:02:32.799814
Time difference: 2 days, 0:00:00
Timedelta 类支持的操作
Operator | Description |
---|---|
Addition (+) | Adds and returns two timedelta objects |
Subtraction (-) | Subtracts and returns two timedelta objects |
Multiplication (*) | Multiplies timedelta object with float or int |
Division (/) | Divides the timedelta object with float or int |
Floor division (//) | Divides the timedelta object with float or int and return the int of floor value of the output |
Modulo (%) | Divides two timedelta object and returns the remainder |
+(timedelta) | Returns the same timedelta object |
-(timedelta) | Returns the resultant of -1*timedelta |
abs(timedelta) | Returns the +(timedelta) if timedelta.days > 1=0 else returns -(timedelta) |
str(timedelta) | Returns a string in the form (+/-) day[s], HH:MM:SS.UUUUUU |
repr(timedelta) | Returns the string representation in the form of the constructor call |
格式化日期时间
格式化日期时间可能非常必要,因为日期表示可能因地而异。就像在某些国家,它可以是 yyyy-mm-dd,而在其他国家,它可以是 dd-mm-yyyy。要格式化Python日期时间,可以使用 strptime 和 strftime 函数。
Python日期时间 strftime
strftime() 方法将给定的日期、时间或日期时间对象转换为给定格式的字符串表示形式。
示例: Python日期时间格式
Python3
# Python program to demonstrate
# strftime() function
from datetime import datetime as dt
# Getting current date and time
now = dt.now()
print("Without formatting", now)
# Example 1
s = now.strftime("%A %m %-Y")
print('\nExample 1:', s)
# Example 2
s = now.strftime("%a %-m %y")
print('\nExample 2:', s)
# Example 3
s = now.strftime("%-I %p %S")
print('\nExample 3:', s)
# Example 4
s = now.strftime("%H:%M:%S")
print('\nExample 4:', s)
Without formatting 2021-08-19 18:16:25.881661
Example 1: Thursday 08 2021
Example 2: Thu 8 21
Example 3: 6 PM 25
Example 4: 18:16:25
注意:有关详细信息,请参阅 strftime() 方法。
Python日期时间 strptime
strptime() 从给定的字符串创建一个日期时间对象。
示例:日期时间 strptime
Python3
# import datetime module from datetime
from datetime import datetime
# consider the time stamps from a list in string
# format DD/MM/YY H:M:S.micros
time_data = ["25/05/99 02:35:8.023", "26/05/99 12:45:0.003",
"27/05/99 07:35:5.523", "28/05/99 05:15:55.523"]
# format the string in the given format : day/month/year
# hours/minutes/seconds-micro seconds
format_data = "%d/%m/%y %H:%M:%S.%f"
# Using strptime with datetime we will format string
# into datetime
for i in time_data:
print(datetime.strptime(i, format_data))
1999-05-25 02:35:08.023000
1999-05-26 12:45:00.003000
1999-05-27 07:35:05.523000
1999-05-28 05:15:55.523000
处理Python DateTime 时区
DateTime 中的时区可用于可能希望根据特定区域的时区显示时间的情况。这可以使用Python的 pytz 模块来完成。该模块提供日期时间转换功能,并帮助用户服务于国际客户群。
Python3
from datetime import datetime
from pytz import timezone
format = "%Y-%m-%d %H:%M:%S %Z%z"
# Current time in UTC
now_utc = datetime.now(timezone('UTC'))
print(now_utc.strftime(format))
timezones = ['Asia/Kolkata', 'Europe/Kiev', 'America/New_York']
for tzone in timezones:
# Convert to Asia/Kolkata time zone
now_asia = now_utc.astimezone(timezone(tzone))
print(now_asia.strftime(format))
2021-08-19 18:27:28 UTC+0000
2021-08-19 23:57:28 IST+0530
2021-08-19 21:27:28 EEST+0300
2021-08-19 14:27:28 EDT-0400