返回介绍

4.5. 日期和时间

发布于 2024-02-10 15:26:30 字数 3802 浏览 0 评论 0 收藏 0

4.5. 日期和时间

4.5.1. 当前时间

from datetime import datetime

print(datetime.today())
print(datetime.now())
print(datetime.now().date())
print(datetime.now().time())
2023-03-11 18:30:34.657155
2023-03-11 18:30:34.657176
2023-03-11
18:30:34.657182			
today = datetime.today()
yesterday = (today - timedelta(days=1)).date()			

4.5.2. 生成时间

from datetime import date
print(date(2002, 12, 31))			

4.5.3. 日期格式化

from datetime import datetime
datetime.today().strftime('%Y-%m-%d.%H:%M:%S')

timepoint = time.strftime('%Y-%m-%d.%H:%M:%S',time.localtime(time.time()))

4.5.4. 字符串转日期

from datetime import datetime

dt_str = '27/10/20 05:23:20'
dt_obj = datetime.strptime(dt_str, '%d/%m/%y %H:%M:%S')

print("The type of the date is now",  type(dt_obj))
print("The date is", dt_obj)			

4.5.5. 日期转字符串

from datetime import date
print(date(2002, 12, 31).strftime('%Y-%m-%d'))			

4.5.6. 日期运算

4.5.6.1. 天数差

	
from datetime import datetime

begin='2023-02-01'
end='2023-02-28'

interval=datetime.strptime(end,'%Y-%m-%d').date() - datetime.strptime(begin,'%Y-%m-%d').date()
print(interval.days)
	
	

4.5.6.2. 月/周 首尾计算

from datetime import timedelta,datetime

now = datetime.now()

# 获取昨天日期:
yesterday = now - timedelta(days=1)
# 获取明天日期:
tomorrow = now + timedelta(days=1)			

	
# 获取本周第一天和最后一天:
this_week_start = now - timedelta(days=now.weekday())
this_week_end = now + timedelta(days=6-now.weekday())

# 获取上周第一天和最后一天:
last_week_start = now - timedelta(days=now.weekday()+7)
last_week_end = now - timedelta(days=now.weekday()+1)

# 获取上月第一天和最后一天:

last_month_end = this_month_start - timedelta(days=1) 
last_month_start = datetime.datetime(last_month_end.year, last_month_end.month, 1)

# 获取本季第一天和最后一天:

month = (now.month - 1) - (now.month - 1) % 3 + 1
this_quarter_start = datetime.datetime(now.year, month, 1)
this_quarter_end = datetime.datetime(now.year, month, calendar.monthrange(now.year, now.month)[1]) 

# 获取上季第一天和最后一天:

last_quarter_end = this_quarter_start - timedelta(days=1)
last_quarter_start = datetime.datetime(last_quarter_end.year, last_quarter_end.month - 2, 1)

# 获取本年第一天和最后一天:

this_year_start = datetime.datetime(now.year, 1, 1)
this_year_end = datetime.datetime(now.year + 1, 1, 1) - timedelta(days=1)

# 获取去年第一天和最后一天:

last_year_end = this_year_start - timedelta(days=1)
last_year_start = datetime.datetime(last_year_end.year, 1, 1) 

	

4.5.7. 日期范围计算

计算两个日期之间的月份

import calendar
import datetime

begin = "2017-11-15"
end = "2018-04-23"


def monthlist(begin, end):
    begin = datetime.datetime.strptime(begin, "%Y-%m-%d")
    end = datetime.datetime.strptime(end, "%Y-%m-%d")

    result = []
    while True:
        if begin.month == 12:
            next = begin.replace(year=begin.year+1, month=1, day=1)
        else:
            next = begin.replace(month=begin.month+1, day=1)
        if next > end:
            break

        day = calendar.monthrange(begin.year, begin.month)[1]

        result.append((begin.strftime("%Y-%m-%d"),
                      begin.replace(day=day).strftime("%Y-%m-%d")))
        begin = next
    result.append((begin.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d")))
    return result


lists = monthlist(begin, end)
print(lists)
for (b, e) in lists:
    print(b, e)

4.5.8. 日期排序

import datetime
 
list_time=["2018-05-01","2018-02-01","2018-07-10","2019-06-01"]
 
list_time1=sorted(list_time,key=lambda date:datetime.datetime.strptime(date,"%Y-%m-%d").timestamp())
 
print('before', list_time)
print('after', list_time1)

print('before', list_time)
print('min', min(list_time1), 'max', max(list_time1))			

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文