1、创建日期和时间对象:
import datetime
date = datetime.date(2023, 6, 15)
print('年月日:',date) # 2023-06-15
time = datetime.time(21, 15, 55)
print('时分秒:',time) # 21:15:55
date_time = datetime.datetime(2023, 6, 15, 21, 15, 55)
print('年月日时分秒:',date_time) # 2023-06-15 21:15:55
2、获取当前日期时间:
import datetime
# 获取当前日期(年月日)
today = datetime.date.today()
print(today) # 2023-06-15
# 获取当前时间(年与日时分秒)
now = datetime.datetime.now()
print(now) # 2023-06-15 20:54:02.429733
3、格式化日期和时间:
import datetime
# 将时间和日期格式化为字符串
now = datetime.datetime.now()
print(now.strftime('%Y-%m-%d %H:%M:%S')) # 2023-06-15 21:03:14
print(now.strftime('%Y/%m/%d %H:%M:%S')) # 2023/06/15 21:04:32
# 将字符串转化为日期和时间对象
today_str = '2023-06-15 21:04:32'
today = datetime.datetime.strptime(today_str, '%Y-%m-%d %H:%M:%S')
print(today) # 2023-06-15 21:04:32
4、计算日期和时间差:
import datetime
# 计算日期差
d1 = datetime.date(2023,6,12)
d2 = datetime.date(2001,6,12)
df = d1 - d2
print('两个日期之间的天数:',df.days) # 8035
# 计算时间差
t1 = datetime.datetime(2023, 6, 15, 21, 15, 55)
t2 = datetime.datetime(2023, 6, 15, 19, 15, 55)
t_time = t1 - t2
print('两个时间之间多少秒:',t_time.seconds) # 7200
5、分别获取年、月、日、时、分、秒,时间戳转换
import datetime
# 分别获取日期中的年 月 日
date = datetime.datetime.now()
print(date)
print('年:', date.year)
print('月:', date.month)
print('日:', date.day)
print('时:', date.hour)
print('分:', date.minute)
print('秒:', date.second)
# 将时间对象转换为时间戳
now = datetime.datetime.now()
timestamp = datetime.datetime.timestamp(now)
print('当前时间转换为时间戳:', timestamp) # 1686835642.493278