Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

datetime object from string, seconds in float

>>> a = "2016-03-22 12:33:45.7565"
>>> datetime.datetime.strptime(a, "%Y-%m-%d %H:%M:%f")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py", line 328, in _strptime
    data_string[found.end():])
ValueError: unconverted data remains: .7565
>>> datetime.datetime.strptime(a, "%Y-%m-%d %H:%M:%S")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py", line 328, in _strptime
    data_string[found.end():])
ValueError: unconverted data remains: .7565

I have used %S and %f but how I can handle seconds if that is type float?

Any help would be appreciated

like image 361
Hackaholic Avatar asked May 06 '16 05:05

Hackaholic


People also ask

How can I get seconds in datetime?

Use the total_seconds() method of a timedelta object to get the number of seconds since the epoch. Use the timestamp() method. If your Python version is greater than 3.3 then another way is to use the timestamp() method of a datetime class to convert datetime to seconds.

How do I convert seconds to datetime in Python?

Use the timedelta() constructor and pass the seconds value to it using the seconds argument. The timedelta constructor creates the timedelta object, representing time in days, hours, minutes, and seconds ( days, hh:mm:ss.ms ) format. For example, datetime.

How do you get seconds in Python?

Use the time. time() function to get the current time in seconds since the epoch as a floating-point number. This method returns the current timestamp in a floating-point number that represents the number of seconds since Jan 1, 1970, 00:00:00. It returns the current time in seconds.


1 Answers

The digits after the decimal point are microseconds, and are formatted separately from the seconds:

>>> a = "2016-03-22 12:33:45.7565"
>>> datetime.datetime.strptime(a, "%Y-%m-%d %H:%M:%S.%f")
datetime.datetime(2016, 3, 22, 12, 33, 45, 756500)
like image 103
snakecharmerb Avatar answered Sep 22 '22 07:09

snakecharmerb