2

Ok, so I'm converting strings to date so far by:

datetime.datetime.fromtimestamp(time.mktime(time.strptime(date_string, DB_TIME_FORMAT)))

But I'm getting some strange results. For example for:

date_string = '2011-08-30 12:52:57.573979'
DB_TIME_FORMAT = '%Y-%m-%d %H:%M:%S.%f'

The result is:

2011-08-30 12:52:57

So I guess my first question is where did the milliseconds go?

My second question would be is there a way to make a "dynamical" string to time conversion? By this I mean, let's say for the format in my previous example, if the milliseconds are not present, instead of getting a ValueError if will still return a normal date. If seconds are missing the same situation and so on?

regards, Bogdan

2
  • I suppose it might be lost with mktime, that should return the unix timestamp in seconds since 1/1/1970. In fact fromtimestamp expects that kind of timestamp. Commented Aug 30, 2011 at 11:35
  • .573979 - looks like microseconds, not milliseconds. Commented Aug 30, 2011 at 12:17

1 Answer 1

2

You're missing the milliseconds because strptime returns a time tuple, which has no milliseconds field, and stores seconds as an integer. From that point forward, your results are missing the milliseconds. The proper way to get milliseconds is to use the datetime module's strptime, like this:

parsed = datetime.datetime.strptime(date_string, DB_TIME_FORMAT)

That also simplifies your solution, since it looks like you want to end up with a datetime anyway.

As far as being relaxed in the accepted format, that's not easy in Python; its date/time modules have no 'auto-detect' the way those for some languages do. Without using third-party libraries, I think you'll be best off catching the exceptions and retrying with a different format. For example:

from datetime import datetime
try: parsed = datetime.strptime(date_string, DB_TIME_FORMAT)
except ValueError:
    parsed = datetime.strptime(date_string, DB_TIME_FORMAT_WITHOUT_MILLISECONDS)

And you could add additional levels for missing seconds and so on.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, don't really remembered why I wanted the timestamp in the first place.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.