0

So this question is more of best way to handle this sort of input in python. Here is an example of input date 2018-12-31 23:59:59.999999. The millisecond part may or may not be part of input.

I am currently using this code to convert this to datetime

input_ts = datetime.datetime.strptime(input_str, '%Y-%m-%dT%H:%M:%S.%f')

But the problem in this case is that it will throw an exception if input string doesn't contain milliseconds part i.e., 2018-12-31 23:59:59

In Java, I could have approached this problem in two ways. (its a pseudo explanation, without taking into account of small boundary checks)

  1. (preferred approach). Check the input string length. if its less than 19 then it is missing milliseconds. Append .000000 to it.

  2. (not preferred). Let the main code parse the string, if it throws an exception, then parse it with new time format i.e., %Y-%m-%dT%H:%M:%S

  3. The third approach could be just strip off milliseconds.

I am not sure if python has anything built-in to handle these kind of situations. Any suggestions?

Dev2017
  • 857
  • 9
  • 31
Em Ae
  • 8,167
  • 27
  • 95
  • 162
  • Why aren't you doing either #1 or #2? – Dan D. Nov 09 '18 at 03:15
  • I can. But since I am still learning Python and based on my past experience, python always have some super concise way to get things done. That's why I am asking – Em Ae Nov 09 '18 at 03:47

2 Answers2

1

You could use python-dateutil library, it is smart enough to parse most of the basic date formats.

import dateutil.parser
dateutil.parser.parse('2018-12-31 23:59:59.999999')
dateutil.parser.parse('2018-12-31 23:59:59')

In case you don't want to install any external libraries, you could iterate over list of different formats as proposed in this answer.

Kamil
  • 1,256
  • 10
  • 17
-1
from datetime import datetime # import datetime class from datetime package

dt = datetime.now() # get current time
dt1 = dt1.strftime('%Y-%m-%d %H:%M:%S') # converting time to string
dt3 = dt2.strptime('2018/5/20','%Y/%m/%d') # converting a string to specified time
TH Z
  • 1
  • 2
  • 3
    While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find [how to write a good answer](https://stackoverflow.com/help/how-to-answer) very helpful. Please edit your answer. – hellow Nov 09 '18 at 09:47