Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert a string date into datetime format in python? [duplicate]

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 
like image 602
PythonEnthusiast Avatar asked Sep 28 '13 14:09

PythonEnthusiast


People also ask

How do I format a date in YYYY MM DD in Python?

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().

How do I convert datetime to date format in Python?

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.


2 Answers

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) 
like image 137
Veedrac Avatar answered Sep 21 '22 15:09

Veedrac


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.

like image 38
Thomas Orozco Avatar answered Sep 24 '22 15:09

Thomas Orozco