How do I convert a a string of datetime into datetime format in python so that it can be compared with another date?
string_date = "2013-09-28 20:30:55.78200" abc = datetime.datetime.now() if abc > string_date : print True
In Python, we can easily format dates and datetime objects with the strftime() function. For example, to format a date as YYYY-MM-DD, pass “%Y-%m-%d” to strftime(). If you want to create a string that is separated by slashes (“/”) instead of dashes (“-“), pass “%Y/%m/%d” to strftime().
In this article, we are going to see how to convert DateTime to date in Python. For this, we will use the strptime() method. This method is used to create a DateTime object from a string. Then we will extract the date from the DateTime object using the date() function.
The particular format for strptime
:
datetime.datetime.strptime(string_date, "%Y-%m-%d %H:%M:%S.%f") #>>> datetime.datetime(2013, 9, 28, 20, 30, 55, 782000)
You should use datetime.datetime.strptime
:
import datetime dt = datetime.datetime.strptime(string_date, fmt)
fmt
will need to be the appropriate format for your string. You'll find the reference on how to build your format here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With