表示时间总共有 3 个相关的类
- datetime.date:表示日期,Attributes: year, month, and day。
- datetime.time:表示时间,Attributes: hour, minute, second, microsecond, and tzinfo。
- datetime.dateime:表示日期和时间,Attributes: year, month, day, hour, minute, second, microsecond, and tzinfo。
- datetime.timedelta:表示一个时间的差值
Import
>>> import time as xtime
# datetime.timezone was added in Python 3.2, So it is normal to get an import error in e.g. Python 2.7.
>>> from datetime import datetime, date, time, timezone, timedelta
Unix TimeStamp
import datetime, time
#获取当前时间戳的整数格式,例如:1553669254
ctime=int(time.time())
timestamp = time.time()
datetime.datetime.utcfromtimestamp(timestamp) #根据时间戮创建一个UTC datetime对象
datetime.datetime.fromtimestamp(time.time()) #根据时间戮创建一个 datetime对象
从字符串中解析出datetime 对象
>>> dt = datetime.fromisoformat('2018-09-22')
>>> dt = datetime.fromisoformat('2018-09-22 16:28:22')
>>> dt = datetime.fromisoformat('2018-09-22 16:28:22.666')
>>> dt = datetime.fromisoformat('2018-09-22 16:28:22.666+08:00')
>>> dt = datetime.strptime('2018-09-22 16:28:22', '%Y-%m-%d %H:%M:%S')
指定 datetime 输出格式
from datetime import datetime
# Sample datetime object
date_object = datetime.now()
# Format the datetime object as a string in the format "DD-MM-YYYY"
formatted_date = date_object.strftime("%d-%m-%Y")
formatted_date = date_object.strptime('2019-10-06','%Y-%m-%d %H:%M:%S')
datetime时间对象实例化
# 构造 datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
>>> datetime(2018, 9, 22, 16, 28, 22)
>>> datetime.today() # 不包含时区信息的当前时间(Naive time)
datetime.datetime(2019, 10, 19, 10, 23, 38, 117425)
>>> datetime.now() # 不包含时区信息的当前时间(当不传入 tz 参数时,和datetime.today()没有区别)
datetime.datetime(2019, 10, 19, 10, 23, 38, 117425)
>>> china_tz = timezone(timedelta(hours=8), 'Asia/Shanghai')
>>> datetime.now(china_tz) # 指定时区对应的当前时间
>>> datetime.utcnow() # 不包含时区信息的当前 UTC 时间
datetime.datetime(2019, 10, 20, 5, 7, 23, 190797)
>>> dt = datetime.combine(date.today(), time(16, 28, 22))
>>> dt = datetime.combine(date.today(), time(16, 28, 22), china_tz)
>>> dt = datetime.fromordinal(736959) # datetime.min以来的天数
datetime对象的类属性
# 类属性
>>> datetime.min # 0001-01-01 00:00:00
>>> datetime.max # 9999-12-31 23:59:59.999999
>>> datetime.resolution # 0:00:00.000001
datetime对象的实例属性
>>> dt = datetime(2018, 9, 22, 16, 28, 22, 999, china_tz)
>>> dt.year # 2018
>>> dt.month # 9
>>> dt.day # 22
>>> dt.hour # 16
>>> dt.minute # 28
>>> dt.second # 22
>>> dt.microsecond # 999
>>> dt.tzinfo # Asia/Shanghai
>>> dt.fold # 0
datetime对象的方法
# 方法
print(dt.date()) # 2018-09-22
print(dt.time()) # 16:28:22.000999
print(dt.timetz()) # 16:28:22.000999+08:00
print(dt.toordinal()) # 736959
print(dt.timestamp()) # 1537604902.000999
print(dt.weekday()) # Monday is 0 and Sunday is 6
print(dt.isoweekday()) # Monday is 1 and Sunday is 7
print(dt.isoformat()) # 2018-09-22T16:28:22.000999+08:00
print(dt.ctime()) # Sat Sep 22 16:28:22 2018
print(dt.strftime('%Y-%m-%d %H:%M:%S')) # 2018-09-22 16:28:22
print(dt.tzname()) # 时区名
print(dt.utcoffset()) # 相对 UTC 时差
print(dt.dst()) # 转换为夏令时
print(dt.timetuple()) # 转成 time.struct_time
print(dt.utctimetuple()) # 转成 time.struct_time
print(dt.astimezone(timezone.utc)) # 时区转换
比较时间
dt1 = datetime(2018, 9, 22, 16, 28, 22)
dt2 = datetime(2018, 9, 22, 16, 28, 23)
if dt1 < dt2:
print(f'{dt1} is before {dt2}')
加减时间
# Usage of time deltas (number of days between two dates, add X days to a date, etc.)
from datetime import datetime
# Define two dates
date1 = datetime(2024, 1, 8) # Example date 1 (current date)
date2 = datetime(2023, 4, 1) # Example date 2
# Calculate the difference in days
difference = date1 - date2
number_of_days = difference.days
number_of_days
#####################
from datetime import datetime, timedelta
# Define a date
original_date = datetime(2024, 1, 8)
# Number of days to add
x_days = 10 # Example: Adding 10 days
# Add days to the date
new_date = original_date + timedelta(days=x_days)
可能出的问题
上面的本地时间(datetime.datetime.today()
),从底层 API实现来说,它会获取本地机器的时间。
而 UTC 时间(datetime.datetime.utcnow()
),从底层 API实现来说,其实是在获取本地机器的时间后,根据当前机器设置的时区信息,计算出 UTC 时间。
这意味着,如果你直接修改了本地机器的时间,则通过 Python API 获取到的时间就会是错误的。
Reference
- datetime — Basic date and time types - https://docs.python.org/3/library/datetime.html
- Python 日期模块 – datetime - https://blog.csdn.net/shangboerds/article/details/82817901