开发者

String to datetime variable format

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 pre开发者_StackOverflow中文版sent, instead of getting a ValueError if will still return a normal date. If seconds are missing the same situation and so on?

regards, Bogdan


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜