1

Some stable genius before my time wrote their dates into the database as strings. Not only that, but the format varies too. I have at least

05.08.1993

and

31.08.1993 00:00:00

Now I want to convert those to datetime objects using strptime(), e.g.

my_date = datetime.datetime.strptime(my_value, '%d.%m.%y')

So now I have to deal with the different formats. I can think of varous clumsy ways to do this, invlvong ugly cascades of ifs or trys. Is there an elegant way to do this?

uwain12345
  • 356
  • 2
  • 21
  • I would suggest using RegEx to determine which format you got at Hand. You could also try using `dateutil.parser.parse()` https://stackoverflow.com/a/23277356/3858121 – Japu_D_Cret Apr 13 '18 at 11:59

4 Answers4

3

I would suggest you use python dateutil

Demo:

from dateutil.parser import parse

a = "05.08.1993"
b = "31.08.1993 00:00:00"

print(parse(a).strftime('%d.%m.%y'))
print(parse(b).strftime('%d.%m.%y'))

Output:

08.05.93
31.08.93

Using Regex:

import re
import datetime

a = "05.08.1993"
b = "31.08.1993 00:00:00"
d = re.search("\d{2}.\d{2}.\d{4}", a)
if d:
    print(datetime.datetime.strptime(d.group(),'%d.%m.%Y').strftime('%d.%m.%y'))

d = re.search("\d{2}.\d{2}.\d{4}", b)
if d:
    print(datetime.datetime.strptime(d.group(),'%d.%m.%Y').strftime('%d.%m.%y'))

Output:

05.08.93
31.08.93
Rakesh
  • 81,458
  • 17
  • 76
  • 113
1

dateutil.parser:

This module offers a generic date/time string parser which is able to parse most known formats to represent a date and/or time.

This module attempts to be forgiving with regards to unlikely input formats, returning a datetime object even for dates which are ambiguous.

Community
  • 1
  • 1
Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
0

For the 2 datatypes you mentioned, it should be sufficient to harness slicing:

my_date = datetime.datetime.strptime(my_value[:10], '%d.%m.%Y')

for a more robust approach, you can use generic date parsers, as other answers mention.

floatingpurr
  • 7,749
  • 9
  • 46
  • 106
0

If it are only 2 patterns, this can be done with re

dates = ('05.08.1993', '31.08.1993 00:00:00')
pattern = re.compile(r'\d{2}\.\d{2}\.\d{4} \d{2}:\d{2}:\d{2}')
strp_pattern = '%d.%m.%Y %H:%M:%S'
strp_pattern_fallback = '%d.%m.%Y'

def parse_dates(dates):
    for date in dates:
        if pattern.match(date):
            yield datetime.datetime.strptime(date, strp_pattern)
        else:
            yield datetime.datetime.strptime(date, strp_pattern_fallback)

list(parse_dates(dates))
[datetime.datetime(1993, 8, 5, 0, 0), datetime.datetime(1993, 8, 31, 0, 0)]
Maarten Fabré
  • 6,938
  • 1
  • 17
  • 36