问题:Python timedelta年
我需要检查自某个日期以来是否已有数年的时间。目前,我timedelta
来自datetime
模块,我不知道如何将其转换为年份。
I need to check if some number of years have been since some date. Currently I’ve got timedelta
from datetime
module and I don’t know how to convert it to years.
回答 0
timedelta
要说明已经过去了多少年,您需要做更多的工作;您还需要知道开始(或结束)日期。(这是a年。)
最好的选择是使用dateutil.relativedelta
object,但这是一个第三方模块。如果你想知道datetime
那是n
几年一些日期(默认为现在),你可以做以下::
from dateutil.relativedelta import relativedelta
def yearsago(years, from_date=None):
if from_date is None:
from_date = datetime.now()
return from_date - relativedelta(years=years)
如果您愿意使用标准库,则答案要复杂一些:
from datetime import datetime
def yearsago(years, from_date=None):
if from_date is None:
from_date = datetime.now()
try:
return from_date.replace(year=from_date.year - years)
except ValueError:
# Must be 2/29!
assert from_date.month == 2 and from_date.day == 29 # can be removed
return from_date.replace(month=2, day=28,
year=from_date.year-years)
如果是2/29,而18年前还没有2/29,则此函数将返回2/28。如果您希望返回3/1,只需将最后一条return
语句更改为:
return from_date.replace(month=3, day=1,
year=from_date.year-years)
您的问题最初是说您想知道自某个日期以来已有多少年了。假设您想要整数年,则可以基于每年365.25天进行猜测,然后使用yearsago
上面定义的任何一个函数进行检查:
def num_years(begin, end=None):
if end is None:
end = datetime.now()
num_years = int((end - begin).days / 365.25)
if begin > yearsago(num_years, end):
return num_years - 1
else:
return num_years
You need more than a timedelta
to tell how many years have passed; you also need to know the beginning (or ending) date. (It’s a leap year thing.)
Your best bet is to use the dateutil.relativedelta
object, but that’s a 3rd party module. If you want to know the datetime
that was n
years from some date (defaulting to right now), you can do the following::
from dateutil.relativedelta import relativedelta
def yearsago(years, from_date=None):
if from_date is None:
from_date = datetime.now()
return from_date - relativedelta(years=years)
If you’d rather stick with the standard library, the answer is a little more complex::
from datetime import datetime
def yearsago(years, from_date=None):
if from_date is None:
from_date = datetime.now()
try:
return from_date.replace(year=from_date.year - years)
except ValueError:
# Must be 2/29!
assert from_date.month == 2 and from_date.day == 29 # can be removed
return from_date.replace(month=2, day=28,
year=from_date.year-years)
If it’s 2/29, and 18 years ago there was no 2/29, this function will return 2/28. If you’d rather return 3/1, just change the last return
statement to read::
return from_date.replace(month=3, day=1,
year=from_date.year-years)
Your question originally said you wanted to know how many years it’s been since some date. Assuming you want an integer number of years, you can guess based on 365.25 days per year and then check using either of the yearsago
functions defined above::
def num_years(begin, end=None):
if end is None:
end = datetime.now()
num_years = int((end - begin).days / 365.25)
if begin > yearsago(num_years, end):
return num_years - 1
else:
return num_years
回答 1
如果您要检查某人是否18岁,请使用 timedelta
在某些极端情况下将无法正常工作。例如,某人出生于2000年1月1日,将在2018年1月1日(恰好包括5个leap年)之后的16575天整整18岁,但某人在2001年1月1日出生的人,将在1月1日在整整6574天之后整整18岁。 2019(包括4个leap年)。因此,如果某人的年龄恰好是6574天,则在不了解有关其出生日期的更多信息的情况下就无法确定他们是17岁还是18岁。
正确的方法是直接从日期中减去年龄,然后减去两年,如果当前月份/日期在出生月份/日期之前,则减去一年。
If you’re trying to check if someone is 18 years of age, using timedelta
will not work correctly on some edge cases because of leap years. For example, someone born on January 1, 2000, will turn 18 exactly 6575 days later on January 1, 2018 (5 leap years included), but someone born on January 1, 2001, will turn 18 exactly 6574 days later on January 1, 2019 (4 leap years included). Thus, you if someone is exactly 6574 days old, you can’t determine if they are 17 or 18 without knowing a little more information about their birthdate.
The correct way to do this is to calculate the age directly from the dates, by subtracting the two years, and then subtracting one if the current month/day precedes the birth month/day.
回答 2
首先,在最详细的级别上,无法完全解决问题。年份长短不一,对于年份长短没有明确的“正确选择”。
也就是说,获得“自然”单位(可能是秒)之间的差异,然后除以该单位与年份之间的比率。例如
delta_in_days / (365.25)
delta_in_seconds / (365.25*24*60*60)
…管他呢。远离月份,因为它们的定义甚至没有几年之久。
First off, at the most detailed level, the problem can’t be solved exactly. Years vary in length, and there isn’t a clear “right choice” for year length.
That said, get the difference in whatever units are “natural” (probably seconds) and divide by the ratio between that and years. E.g.
delta_in_days / (365.25)
delta_in_seconds / (365.25*24*60*60)
…or whatever. Stay away from months, since they are even less well defined than years.
回答 3
这是一个更新的DOB函数,该函数以与人类相同的方式计算生日:
import datetime
import locale
# Source: https://en.wikipedia.org/wiki/February_29
PRE = [
'US',
'TW',
]
POST = [
'GB',
'HK',
]
def get_country():
code, _ = locale.getlocale()
try:
return code.split('_')[1]
except IndexError:
raise Exception('Country cannot be ascertained from locale.')
def get_leap_birthday(year):
country = get_country()
if country in PRE:
return datetime.date(year, 2, 28)
elif country in POST:
return datetime.date(year, 3, 1)
else:
raise Exception('It is unknown whether your country treats leap year '
+ 'birthdays as being on the 28th of February or '
+ 'the 1st of March. Please consult your country\'s '
+ 'legal code for in order to ascertain an answer.')
def age(dob):
today = datetime.date.today()
years = today.year - dob.year
try:
birthday = datetime.date(today.year, dob.month, dob.day)
except ValueError as e:
if dob.month == 2 and dob.day == 29:
birthday = get_leap_birthday(today.year)
else:
raise e
if today < birthday:
years -= 1
return years
print(age(datetime.date(1988, 2, 29)))
Here’s a updated DOB function, which calculates birthdays the same way humans do:
import datetime
import locale
# Source: https://en.wikipedia.org/wiki/February_29
PRE = [
'US',
'TW',
]
POST = [
'GB',
'HK',
]
def get_country():
code, _ = locale.getlocale()
try:
return code.split('_')[1]
except IndexError:
raise Exception('Country cannot be ascertained from locale.')
def get_leap_birthday(year):
country = get_country()
if country in PRE:
return datetime.date(year, 2, 28)
elif country in POST:
return datetime.date(year, 3, 1)
else:
raise Exception('It is unknown whether your country treats leap year '
+ 'birthdays as being on the 28th of February or '
+ 'the 1st of March. Please consult your country\'s '
+ 'legal code for in order to ascertain an answer.')
def age(dob):
today = datetime.date.today()
years = today.year - dob.year
try:
birthday = datetime.date(today.year, dob.month, dob.day)
except ValueError as e:
if dob.month == 2 and dob.day == 29:
birthday = get_leap_birthday(today.year)
else:
raise e
if today < birthday:
years -= 1
return years
print(age(datetime.date(1988, 2, 29)))
回答 4
得到天数,然后除以365.2425(平均公历年)为年。除以30.436875(平均公历月)为月。
Get the number of days, then divide by 365.2425 (the mean Gregorian year) for years. Divide by 30.436875 (the mean Gregorian month) for months.
回答 5
def age(dob):
import datetime
today = datetime.date.today()
if today.month < dob.month or \
(today.month == dob.month and today.day < dob.day):
return today.year - dob.year - 1
else:
return today.year - dob.year
>>> import datetime
>>> datetime.date.today()
datetime.date(2009, 12, 1)
>>> age(datetime.date(2008, 11, 30))
1
>>> age(datetime.date(2008, 12, 1))
1
>>> age(datetime.date(2008, 12, 2))
0
def age(dob):
import datetime
today = datetime.date.today()
if today.month < dob.month or \
(today.month == dob.month and today.day < dob.day):
return today.year - dob.year - 1
else:
return today.year - dob.year
>>> import datetime
>>> datetime.date.today()
datetime.date(2009, 12, 1)
>>> age(datetime.date(2008, 11, 30))
1
>>> age(datetime.date(2008, 12, 1))
1
>>> age(datetime.date(2008, 12, 2))
0
回答 6
您需要多精确? td.days / 365.25
如果您担心leap年,它将使您更加接近。
How exact do you need it to be? td.days / 365.25
will get you pretty close, if you’re worried about leap years.
回答 7
此处未提及的另一个第三方库lib是mxDateTime(python datetime
和3rd party的前身timeutil
)可用于此任务。
前面提到的yearsago
是:
from mx.DateTime import now, RelativeDateTime
def years_ago(years, from_date=None):
if from_date == None:
from_date = now()
return from_date-RelativeDateTime(years=years)
第一个参数应该是一个DateTime
实例。
要转换普通datetime
到DateTime
你可以使用这个1秒精度):
def DT_from_dt_s(t):
return DT.DateTimeFromTicks(time.mktime(t.timetuple()))
或1微秒的精度:
def DT_from_dt_u(t):
return DT.DateTime(t.year, t.month, t.day, t.hour,
t.minute, t.second + t.microsecond * 1e-6)
是的,即使与使用timeutil(由Rick Copeland建议)相比,为有问题的单个任务添加依赖绝对是一个过大的杀伤力。
Yet another 3rd party lib not mentioned here is mxDateTime (predecessor of both python datetime
and 3rd party timeutil
) could be used for this task.
The aforementioned yearsago
would be:
from mx.DateTime import now, RelativeDateTime
def years_ago(years, from_date=None):
if from_date == None:
from_date = now()
return from_date-RelativeDateTime(years=years)
First parameter is expected to be a DateTime
instance.
To convert ordinary datetime
to DateTime
you could use this for 1 second precision):
def DT_from_dt_s(t):
return DT.DateTimeFromTicks(time.mktime(t.timetuple()))
or this for 1 microsecond precision:
def DT_from_dt_u(t):
return DT.DateTime(t.year, t.month, t.day, t.hour,
t.minute, t.second + t.microsecond * 1e-6)
And yes, adding the dependency for this single task in question would definitely be an overkill compared even with using timeutil (suggested by Rick Copeland).
回答 8
最后,您遇到的是数学问题。如果每隔4年我们有额外的一天,那么可以在几天之内(而不是365天,而是365 * 4 +1)潜水timedelta,那么您的时间就是4年。然后再将其除以4。timedelta /((365 * 4)+1)/ 4 = timedelta * 4 /(365 * 4 +1)
In the end what you have is a maths issue. If every 4 years we have an extra day lets then dived the timedelta in days, not by 365 but 365*4 + 1, that would give you the amount of 4 years. Then divide it again by 4.
timedelta / ((365*4) +1) / 4 = timedelta * 4 / (365*4 +1)
回答 9
这是我制定的解决方案,希望对您有所帮助;-)
def menor_edad_legal(birthday):
""" returns true if aged<18 in days """
try:
today = time.localtime()
fa_divuit_anys=date(year=today.tm_year-18, month=today.tm_mon, day=today.tm_mday)
if birthday>fa_divuit_anys:
return True
else:
return False
except Exception, ex_edad:
logging.error('Error menor de edad: %s' % ex_edad)
return True
This is the solution I worked out, I hope can help ;-)
def menor_edad_legal(birthday):
""" returns true if aged<18 in days """
try:
today = time.localtime()
fa_divuit_anys=date(year=today.tm_year-18, month=today.tm_mon, day=today.tm_mday)
if birthday>fa_divuit_anys:
return True
else:
return False
except Exception, ex_edad:
logging.error('Error menor de edad: %s' % ex_edad)
return True
回答 10
即使该线程已经死了,我还是可以为我面临的这个同样的问题提出一个可行的解决方案。这是(日期是格式为dd-mm-yyyy的字符串):
def validatedate(date):
parts = date.strip().split('-')
if len(parts) == 3 and False not in [x.isdigit() for x in parts]:
birth = datetime.date(int(parts[2]), int(parts[1]), int(parts[0]))
today = datetime.date.today()
b = (birth.year * 10000) + (birth.month * 100) + (birth.day)
t = (today.year * 10000) + (today.month * 100) + (today.day)
if (t - 18 * 10000) >= b:
return True
return False
Even though this thread is already dead, might i suggest a working solution for this very same problem i was facing. Here it is (date is a string in the format dd-mm-yyyy):
def validatedate(date):
parts = date.strip().split('-')
if len(parts) == 3 and False not in [x.isdigit() for x in parts]:
birth = datetime.date(int(parts[2]), int(parts[1]), int(parts[0]))
today = datetime.date.today()
b = (birth.year * 10000) + (birth.month * 100) + (birth.day)
t = (today.year * 10000) + (today.month * 100) + (today.day)
if (t - 18 * 10000) >= b:
return True
return False
回答 11
此函数返回两个日期之间的年份差(以ISO格式作为字符串,但是可以轻松修改以采用任何格式)
import time
def years(earlydateiso, laterdateiso):
"""difference in years between two dates in ISO format"""
ed = time.strptime(earlydateiso, "%Y-%m-%d")
ld = time.strptime(laterdateiso, "%Y-%m-%d")
#switch dates if needed
if ld < ed:
ld, ed = ed, ld
res = ld[0] - ed [0]
if res > 0:
if ld[1]< ed[1]:
res -= 1
elif ld[1] == ed[1]:
if ld[2]< ed[2]:
res -= 1
return res
this function returns the difference in years between two dates (taken as strings in ISO format, but it can easily modified to take in any format)
import time
def years(earlydateiso, laterdateiso):
"""difference in years between two dates in ISO format"""
ed = time.strptime(earlydateiso, "%Y-%m-%d")
ld = time.strptime(laterdateiso, "%Y-%m-%d")
#switch dates if needed
if ld < ed:
ld, ed = ed, ld
res = ld[0] - ed [0]
if res > 0:
if ld[1]< ed[1]:
res -= 1
elif ld[1] == ed[1]:
if ld[2]< ed[2]:
res -= 1
return res
回答 12
我建议Pyfdate
什么是pyfdate?
鉴于Python的目标是成为功能强大且易于使用的脚本语言,因此其用于日期和时间的功能并不像应该的那样友好。pyfdate的目的是通过提供与日期和时间一起使用的功能来补救这种情况,这些功能与Python的其余部分一样强大且易于使用。
本教程
I’ll suggest Pyfdate
What is pyfdate?
Given Python’s goal to be a powerful and easy-to-use scripting
language, its features for working
with dates and times are not as
user-friendly as they should be. The
purpose of pyfdate is to remedy that
situation by providing features for
working with dates and times that are
as powerful and easy-to-use as the
rest of Python.
the tutorial
回答 13
import datetime
def check_if_old_enough(years_needed, old_date):
limit_date = datetime.date(old_date.year + years_needed, old_date.month, old_date.day)
today = datetime.datetime.now().date()
old_enough = False
if limit_date <= today:
old_enough = True
return old_enough
def test_ages():
years_needed = 30
born_date_Logan = datetime.datetime(1988, 3, 5)
if check_if_old_enough(years_needed, born_date_Logan):
print("Logan is old enough")
else:
print("Logan is not old enough")
born_date_Jessica = datetime.datetime(1997, 3, 6)
if check_if_old_enough(years_needed, born_date_Jessica):
print("Jessica is old enough")
else:
print("Jessica is not old enough")
test_ages()
这是Carrousel操作员在Logan的Run电影中运行的代码;)
https://zh.wikipedia.org/wiki/Logan%27s_Run_(电影)
import datetime
def check_if_old_enough(years_needed, old_date):
limit_date = datetime.date(old_date.year + years_needed, old_date.month, old_date.day)
today = datetime.datetime.now().date()
old_enough = False
if limit_date <= today:
old_enough = True
return old_enough
def test_ages():
years_needed = 30
born_date_Logan = datetime.datetime(1988, 3, 5)
if check_if_old_enough(years_needed, born_date_Logan):
print("Logan is old enough")
else:
print("Logan is not old enough")
born_date_Jessica = datetime.datetime(1997, 3, 6)
if check_if_old_enough(years_needed, born_date_Jessica):
print("Jessica is old enough")
else:
print("Jessica is not old enough")
test_ages()
This is the code that the Carrousel operator was running in Logan’s Run film ;)
https://en.wikipedia.org/wiki/Logan%27s_Run_(film)
回答 14
我遇到这个问题,发现亚当斯回答了最有帮助的https://stackoverflow.com/a/765862/2964689
但是没有python方法的示例,但这是我最终使用的方法。
输入:日期时间对象
输出:整年的整数年龄
def age(birthday):
birthday = birthday.date()
today = date.today()
years = today.year - birthday.year
if (today.month < birthday.month or
(today.month == birthday.month and today.day < birthday.day)):
years = years - 1
return years
I came across this question and found Adams answer the most helpful https://stackoverflow.com/a/765862/2964689
But there was no python example of his method but here’s what I ended up using.
input: datetime object
output: integer age in whole years
def age(birthday):
birthday = birthday.date()
today = date.today()
years = today.year - birthday.year
if (today.month < birthday.month or
(today.month == birthday.month and today.day < birthday.day)):
years = years - 1
return years
回答 15
我喜欢John Mee的解决方案,因为它简单易用,我也不担心在2月28日或3月1日(不是a年)如何确定2月29日出生的人的年龄。但这是他的代码的一些调整我认为可以解决这些投诉:
def age(dob):
import datetime
today = datetime.date.today()
age = today.year - dob.year
if ( today.month == dob.month == 2 and
today.day == 28 and dob.day == 29 ):
pass
elif today.month < dob.month or \
(today.month == dob.month and today.day < dob.day):
age -= 1
return age
I liked John Mee’s solution for its simplicity, and I am not that concerned about how, on Feb 28 or March 1 when it is not a leap year, to determine age of people born on Feb 29. But here is a tweak of his code which I think addresses the complaints:
def age(dob):
import datetime
today = datetime.date.today()
age = today.year - dob.year
if ( today.month == dob.month == 2 and
today.day == 28 and dob.day == 29 ):
pass
elif today.month < dob.month or \
(today.month == dob.month and today.day < dob.day):
age -= 1
return age