aeupinhere
aeupinhere

Reputation: 2983

Python DateTime Issues

All,

I have come across an API that is returning bad dates as strings. For example, sometimes I come across a record that returns '1856-00-00 00:00:00' which does not work in my application. I can easily convert the string to a datetime object but how can I evaluate the same object to tell if the day and month are both 00? Here is what I have so far.

try:
    date_taken = None
    if x.has_key('datetaken'):
        date_taken = x['datetaken']
        gooddate = dateutil.parser.parse(date_taken)
    if gooddate < datetime.datetime(1960, 01, 01, 00, 00, 00):
        fixdate = str(gooddate)   
except Exception as err:
    logger.error('datetaken: %s', err)

I would like to convert the bad datetime objects to January 1st 1960.

Adam

Upvotes: 2

Views: 220

Answers (2)

jcomeau_ictx
jcomeau_ictx

Reputation: 38412

>>> import datetime, dateutil, dateutil.parser
>>> mindate = datetime.datetime(1960, 01, 01, 00, 00, 00)
>>> gooddate = None
>>> try:
...  gooddate = dateutil.parser.parse('1856-00-00 00:00:00')
... except ValueError:
...  pass
... except Exception as err:
...  raise err
... 
>>> if gooddate is None or gooddate < mindate:
...  gooddate = mindate
... 
>>> gooddate
datetime.datetime(1960, 1, 1, 0, 0)

Upvotes: 0

Rob Wouters
Rob Wouters

Reputation: 16327

Just try parsing it and catch the exception:

from datetime import datetime

string = '1856-00-00 00:00:00'

try:
    date = datetime.strptime(string, '%Y-%m-%d %H:%M:%S')
except ValueError:
    date = datetime(1960, 1, 1, 0, 0, 0)

print(date)

Upvotes: 2

Related Questions