I am parsing some datetime strings in Python 2.7, using datetime.strptime
. I want to assume that a date is prior to now.
But strptime's %y
operator does not do this by default:
d = '10/12/68'
n = datetime.strptime(d, '%d/%m/%y')
print n
2068-12-10 00:00:00
Is there any way I can get Python to assume that 68
is 1968
, as it would be in common usage?
Or should I just parse the string and insert 19
or 20
, as appropriate, manually?
If your input is in the local timezone:
from datetime import date
then = datetime.strptime('10/12/68', '%d/%m/%y').date()
if date.today() <= then: # *then* must be in the past
then = then.replace(year=then.year - 100)
It should work ok until 2100 (excluding). See here for more details on arithmetic with calendar years.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With