我有一个日期“10/10/11(m-d-y)”,我想用Python脚本添加5天。请考虑一个在月底也适用的通用解决方案。
我使用以下代码:
import re
from datetime import datetime
StartDate = "10/10/11"
Date = datetime.strptime(StartDate, "%m/%d/%y")
打印日期->正在打印'2011-10-10 00:00:00'
现在我想在这个日期上加5天。我使用了以下代码:
EndDate = Date.today()+timedelta(days=10)
返回以下错误:
name 'timedelta' is not defined
我刚看到一条旧帖子:
我查过了,但大部分答案都是一样的。我喜欢其中的两个答案,所以我想检查一下这两种方法的效率。
第一种方法:使用DateTime模块
第二种方法:利用熊猫的图书馆
所以我运行了大约10k次测试,熊猫库方法要慢得多。所以我建议使用内置的DateTime模块。
from datetime import date, timedelta
import pandas as pd
import timeit
def using_datetime():
pre_date = date(2013, 10, 10)
day_date = pre_date + timedelta(days=5)
return day_date
def using_pd():
start_date = "10/10/2022"
pd_date = pd.to_datetime(start_date)
end_date = pd_date + pd.DateOffset(days=5)
return end_date
for func in [using_datetime, using_pd]:
print(f"{func.__name__} Time Took: ", timeit.timeit(stmt=func, number=10000))
# Output
# using_datetime Time Took: 0.009390000021085143
# using_pd Time Took: 2.1051381999859586
一般来说,你现在已经有了一个答案,但也许我创建的类也会有帮助。对我来说,它解决了我在Pyhon项目中遇到的所有需求。
class GetDate:
def __init__(self, date, format="%Y-%m-%d"):
self.tz = pytz.timezone("Europe/Warsaw")
if isinstance(date, str):
date = datetime.strptime(date, format)
self.date = date.astimezone(self.tz)
def time_delta_days(self, days):
return self.date + timedelta(days=days)
def time_delta_hours(self, hours):
return self.date + timedelta(hours=hours)
def time_delta_seconds(self, seconds):
return self.date + timedelta(seconds=seconds)
def get_minimum_time(self):
return datetime.combine(self.date, time.min).astimezone(self.tz)
def get_maximum_time(self):
return datetime.combine(self.date, time.max).astimezone(self.tz)
def get_month_first_day(self):
return datetime(self.date.year, self.date.month, 1).astimezone(self.tz)
def current(self):
return self.date
def get_month_last_day(self):
lastDay = calendar.monthrange(self.date.year, self.date.month)[1]
date = datetime(self.date.year, self.date.month, lastDay)
return datetime.combine(date, time.max).astimezone(self.tz)
如何使用
self.tz = pytz.timezone("Europe/Warsaw") - here you define Time Zone you want to use in project
GetDate("2019-08-08").current() - this will convert your string date to time aware object with timezone you defined in pt 1. Default string format is format="%Y-%m-%d" but feel free to change it. (eg. GetDate("2019-08-08 08:45", format="%Y-%m-%d %H:%M").current())
GetDate("2019-08-08").get_month_first_day() returns given date (string or object) month first day
GetDate("2019-08-08").get_month_last_day() returns given date month last day
GetDate("2019-08-08").minimum_time() returns given date day start
GetDate("2019-08-08").maximum_time() returns given date day end
GetDate("2019-08-08").time_delta_days({number_of_days}) returns given date + add {number of days} (you can also call: GetDate(timezone.now()).time_delta_days(-1) for yesterday)
GetDate("2019-08-08").time_delta_haours({number_of_hours}) similar to pt 7 but working on hours
GetDate("2019-08-08").time_delta_seconds({number_of_seconds}) similar to pt 7 but working on seconds