Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a String into a datetime object in python

I have a string field like this..

2011-09-04 23:44:30.801000

and now I need to convert it to a datetime object in python so that I can calculate the difference between two datetime objects.

like image 710
diamond Avatar asked Mar 20 '26 10:03

diamond


1 Answers

You should use datetime.datetime.strptime(), which converts a string and date format into a datetime.datetime object.

The format fields (e.g., %Y denotes four-digit year) are specified in the Python documentation.

>>> import datetime
>>> s      = '2011-09-04 23:44:30.801000'
>>> format = '%Y-%m-%d %H:%M:%S.%f'
>>> date=datetime.datetime.strptime(s, format)
>>> date
datetime.datetime(2011, 9, 4, 23, 44, 30, 801000)
like image 189
Adam Matan Avatar answered Mar 22 '26 01:03

Adam Matan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!