How to convert string to datetime in python

I have a date string in the following format. 2011-03-07 How to convert this to datetime in python?

+4
source share
5 answers

Try using the following code that uses strptime from the datetime module:

 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;)

+18
source

You can use datetime.date :

 >>> import datetime >>> s = '2011-03-07' >>> datetime.date(*map(int, s.split('-'))) datetime.date(2011, 3, 7) 
+3
source

Try the following:

 import datetime print(datetime.datetime.strptime('2011-03-07', '%Y-%m-%d')) 
+2
source

This will open datetime.datetime.strptime and its strftime sister for this:

 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.

+1
source

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.

+1
source

Source: https://habr.com/ru/post/1342630/


All Articles