10
from datetime import datetime

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

results with 
1900-08-21 15:26:00

how can I write in pythonic way so that when there's no year, take the current year as default (2013)?

I checked and strftime function doesn't have option to change the default.. maybe another time libraries can do?

thx

eligro
  • 785
  • 3
  • 13
  • 23
  • If you don't object to 3rd party libs, you could use the [dateutil](http://labix.org/python-dateutil) module. It's [parser](http://labix.org/python-dateutil#head-a23e8ae0a661d77b89dfb3476f85b26f0b30349c) method takes a default date that is used to fill in missing information from a parsed string. – SethMMorton Aug 22 '13 at 05:30

2 Answers2

7

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')
Mario Rossi
  • 7,651
  • 27
  • 37
  • 1
    Remember, though, that datetime objects are immutable, so replace here returns a new datetime object. – cge Aug 22 '13 at 00:05
  • @cge Thanks for that one. With a small change I made it clear in the text. – Mario Rossi Aug 22 '13 at 00:08
  • I can't hack for specific cases. it's a function that receives hundreds of date-times and formats, and trying to match them.. – eligro Aug 22 '13 at 00:12
  • 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. – Mario Rossi Aug 22 '13 at 00:16
  • @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. – cge Aug 22 '13 at 23:24
  • @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. – Mario Rossi Sep 15 '18 at 01:19
1

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)
Avi Gaur
  • 111
  • 6