-1

I need to parse a string into a datetime with python, for example:

datetime.datetime.strptime('2018-06-29 08:15:27.243860', '%Y-%m-%d %H:%M:%S.%f')

But sometime I didn't know if the input is 2018-06-29 08:15:27.243860 or 2018-06-29 08:15:27 (without milliseconds).

If I tried

datetime.datetime.strptime('2018-06-29 08:15:27', '%Y-%m-%d %H:%M:%S.%f')

I got an exception

ValueError: time data '2018-06-29 08:15:27' does not match format '%Y-%m-%d %H:%M:%S.%f'

Is there any way to use same format to '2018-06-29 08:15:27.243860' and '2018-06-29 08:15:27'?

I don't care about milliseconds, I want to drop them.

martineau
  • 119,623
  • 25
  • 170
  • 301
Streamer
  • 25
  • 4
  • 1
    Since any inout matching your pattern has a fixed length, why not just drop any input that is too much? For example ``datetime.datetime.strptime('2018-06-29 08:15:27.243860'[:19], '%Y-%m-%d %H:%M:%S')``. – MisterMiyagi Feb 17 '21 at 18:50

1 Answers1

1

use datetime.fromisoformat and replace microsecond with zero:


s = ('2018-06-29 08:15:27.243860', '2018-06-29 08:15:27')

for t in s:
    print(datetime.fromisoformat(t).replace(microsecond=0))
2018-06-29 08:15:27
2018-06-29 08:15:27

It's efficient as well.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72