I need to parse strings representing 6-digit dates in the format yymmdd
where yy
ranges from 59 to 05 (1959 to 2005). According to the time
module docs, Python's default pivot year is 1969 which won't work for me.
Is there an easy way to override the pivot year, or can you suggest some other solution? I am using Python 2.7. Thanks!
Python DateTime Format – dd-mm-YYYY dd meaning day represented with two digit string, mm is month represented with two digit string and YYYY is year represented with four digit string. The format string would be “%d-%m-%Y”.
The correct pattern to use is '%d-%b-%y' here, where %b matches an abbreviated month name.
Python has a built-in method to parse dates, strptime . This example takes the string “2020–01–01 14:00” and parses it to a datetime object. The documentation for strptime provides a great overview of all format-string options.
Parse(String, IFormatProvider, DateTimeStyles) Converts the string representation of a date and time to its DateTime equivalent by using culture-specific format information and a formatting style.
I'd use datetime
and parse it out normally. Then I'd use datetime.datetime.replace
on the object if it is past your ceiling date -- Adjusting it back 100 yrs.:
import datetime dd = datetime.datetime.strptime(date,'%y%m%d') if dd.year > 2005: dd = dd.replace(year=dd.year-100)
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