python-标准库datetime模块的使用

python-标准库datetime模块

1. python-标准库datetime模块

  • datetime库用于处理更复杂的日期和时间。
    提供以下几个类:

    方法 描述
    datetime.date 日期,年月日组成
    datetime.datetime 包括日期和时间
    datetime.time 时间,时分秒及微秒组成
    datetime.timedelta 时间间隔
    datetime.tzinfo 时区信息对象
    date.today 获取当前时间
  • 示例

    from datetime import date, datetime
    # 将当前系统时间转换指定格式
    date.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')
    # 获取当前系统时间
    date.isoformat(date.today())
    # 将时间戳转换指定格式
    date_array = datetime.fromtimestamp(time.time())
    date_array.strftime("%Y-%m-%d %H:%M:%S")
    
    
    # 获取昨天日期
    from datetime import date, timedelta
    yesterday = date.today() - timedelta(days=1)
    yesterday = date.isoformat(yesterday)
    print(yesterday)
    
    # 获取明天日期
    tomorrow = date.today() + timedelta(days=1)
    # 将时间对象格式化
    tomorrow = date.isoformat(tomorrow)
    print(tomorrow)
    

2. 案例

#!/usr/bin/env python3
# _*_ coding: utf-8 _*_
# Author:shichao
# File: .py

import time
from datetime import date, datetime
# 将当前系统时间转换指定格式
print(date.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S'))
# 获取当前系统时间
print(date.isoformat(date.today()))
# 将时间戳转换指定格式
date_array = datetime.fromtimestamp(time.time())
print(date_array.strftime("%Y-%m-%d %H:%M:%S"))


# 获取昨天日期
from datetime import date, timedelta
yesterday = date.today() - timedelta(days=1)
yesterday = date.isoformat(yesterday)
print(yesterday)


# 获取明天日期
from datetime import date, timedelta
tomorrow = date.today() + timedelta(days=1)
# 将时间对象格式化
tomorrow = date.isoformat(tomorrow)
print(tomorrow)

3. 案例-判断剩余多少天

#!/usr/bin/env python3
# _*_ coding: utf-8 _*_
# Author:shichao
# File: .py

import time
from datetime import date, datetime

# 获取当前时间
ini_time_str = date.strftime(datetime.now(), '%Y/%m/%d %H:%M:%S')

# 到期时间
end_time_str = '2023/9/1 7:48:50'


# 格式化当前时间格式
ini_time = datetime.strptime(ini_time_str, '%Y/%m/%d %H:%M:%S')
end_time = datetime.strptime(end_time_str, '%Y/%m/%d %H:%M:%S')
res = (end_time-ini_time).days

print("还剩余多少 %s 天" %res)
posted @ 2023-01-13 10:27  七月流星雨  阅读(80)  评论(0编辑  收藏  举报