Using datetime.strptime with default year as current year
Asked Answered
L

2

11

Parsing a date string using datetime.strptime such as:

from datetime import datetime       
datetime.strptime('AUG21  3:26PM', '%b%d  %I:%M%p')

Results in

1900-08-21 15:26:00

How can I write something similar in a Pythonic way so that, when there's no year in the date string, it takes the current year as default (e.g 2013) rather than 1900?

I've checked the documentation of the strftime function and it doesn't have an option to change the default year. Maybe another time library can do so?

Lorenzo answered 21/8, 2013 at 23:47 Comment(1)
If you don't object to 3rd party libs, you could use the dateutil module. It's parser method takes a default date that is used to fill in missing information from a parsed string.Stichous
B
9

Parse the date as you are already doing, and then

date= date.replace(2013)

This is one of simplest solution with the modules you are using.

Thinking better about it, you will probably face a problem next Feb 29.

input= 'Aug21  3:26PM'
output= datetime.datetime.strptime('2013 '+ input ,'%Y %b%d  %I:%M%p')
Boccioni answered 22/8, 2013 at 0:3 Comment(6)
Remember, though, that datetime objects are immutable, so replace here returns a new datetime object.Maureen
@Maureen Thanks for that one. With a small change I made it clear in the text.Boccioni
I can't hack for specific cases. it's a function that receives hundreds of date-times and formats, and trying to match them..Lorenzo
Then modify datetime source and recompile. This is an old issue, and I don't know of any other solution. Only alternative I can think of (because modifying library modules is definitely too drastic and I can't believe I just recommended it :-) ) is checking if the format (and thus date) comes with a year. If not, then you "hack" them. Otherwise, you leave them as they are.Boccioni
@MarioRossi: a decent option would be to subclass the datetime class, and write a wrapper for strptime that calls the parent strptime, then applies defaults if necessary.Maureen
@cge: True, though one disadvantage would be dependency on implementation details / internals of code you don't control. IOW, datetime implementors surely fell free to make changes as long as they do not affect clients. However, the concept of "client" rarely include subclasses.Boccioni
F
0

You can find out today's date to replace year for dynamic replacement.

datetime.strptime('%b%d  %I:%M%p', 'AUG21  3:26PM').replace(year=datetime.today().year)
Forenamed answered 13/6, 2021 at 12:4 Comment(1)
There are two bugs in your one line of code: you have the parameters to strptime backwards and this wouldn't work for FEB29 (because in the absence of an explicit year, it will assume 1900 which was not a leap year).Tricot

© 2022 - 2024 — McMap. All rights reserved.