snippets / convert '2007-11-08 16:17:17.375000' in a datetime and keep microseconds

Language: Python - First posted by benoitc on 2007-11-8 17:10 (1 year)
Link to the snippet: http://www.friendsnippets.org/snippet/116/

strptime don't take microseconds in python 2.x. Here is a quickway to add them to a datetime object.

1 >>> from datetime import datetime
2 >>> from time import strptime
3 >>> date_str='2007-11-08 16:17:17.375000'
4 >>> d = datetime(*strptime(date_str[:19],"%Y-%m-%d %H:%M:%S")[0:6])
5 >>> d = d.replace(microsecond=eval(date_str[20:]))
6 >>> print d
7 2007-11-08 16:17:17.375000
In order to post a comment, you should have a friendsnippet account. Please sign-in.

2 comments

  • November 9th 2007 at 10:57

    to convert it in an unix timestamp :

    1 !python
    2 #python 2.4
    3 >>> time.mktime(d.timetuple()) + d.microsecond / 1e6
    4 1194535037.375
  • November 8th 2007 at 17:22
    1 # python >= 2.5
    2 import datetime
    3 d = datetime.strptime(date_str[:19],"%Y-%m-%d %H:%M:%S")
    4 d = d.replace(microsecond=eval(date_str[20:]))
    5 print d
Nov '07
  • strptime don't take microseconds in python 2.x. Here is a quickway to add them to a datetime object.

Common Tags


Related snippets


snippet History

Nov '07