I have a date string in the following format. 2011-03-07 How to convert this to datetime in python?
Try using the following code that uses strptime from the datetime module:
strptime
from datetime import datetime datetime.strptime('2011-03-07','%Y-%m-%d')
I note that this (and many other solutions) is trivially easy to find with Google;)
You can use datetime.date :
datetime.date
>>> import datetime >>> s = '2011-03-07' >>> datetime.date(*map(int, s.split('-'))) datetime.date(2011, 3, 7)
Try the following:
import datetime print(datetime.datetime.strptime('2011-03-07', '%Y-%m-%d'))
This will open datetime.datetime.strptime and its strftime sister for this:
datetime.datetime.strptime
strftime
from datetime import datetime time_obj = datetime.strptime("2011-03-07", "%Y-%m-%d")
Used for parsing and forming from datetime to string and vice versa.
The datetime.datetime object from the standard library has a constructor datetime.strptime (date_string, format), which is likely to be more reliable than any manual string manipulations that you do yourself.
Read strptime strings to determine how to specify the desired format.
Source: https://habr.com/ru/post/1342630/More articles:What is the best way to determine if NamedDataSlot exists - multithreadingjquery closest doesn't want to work - javascriptHow to combine two lines in the name of another line and call this line? - stringProgress bar when using Dropbox api - c #Define browser and OS using CSS? - cssHow to match and combine a C array into C # code - c ++setData on intent prevents sendBroadcast from working? - androidget key value from django / python dictionary - pythonReturns razor-processed Javascript as ViewResult from a controller - asp.netArray in a Java program of fancy behavior - javaAll Articles