Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse string dates with 2-digit year?

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!

like image 800
blah238 Avatar asked May 17 '13 02:05

blah238


People also ask

How do you get a two digit year in Python?

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”.

How do you convert a two digit year to a four digit year in Python?

The correct pattern to use is '%d-%b-%y' here, where %b matches an abbreviated month name.

How do you parse a date in python?

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.

What is date/time parse?

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.


1 Answers

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) 
like image 196
mgilson Avatar answered Sep 18 '22 12:09

mgilson