Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string into Date type on Python [duplicate]

I have this string:

'2012-02-10' # (year-month-day)

and I need it to be as date type for me to use the date function isoweekday().

Does anyone know how I can convert this string into a date?

like image 867
Lucas Rezende Avatar asked Feb 29 '12 18:02

Lucas Rezende


People also ask

Can we convert string to datetime in Python?

We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.

How do I turn a string into a date?

Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.

How do I change the data type of a date in Python?

The date column is indeed a string, which—remember—is denoted as an object type in Python. You can convert it to the datetime type with the . to_datetime() method in pandas .


5 Answers

While it seems the question was answered per the OP's request, none of the answers give a good way to get a datetime.date object instead of a datetime.datetime. So for those searching and finding this thread:

datetime.date has no .strptime method; use the one on datetime.datetime instead and then call .date() on it to receive the datetime.date object.

Like so:

>>> from datetime import datetime >>> datetime.strptime('2014-12-04', '%Y-%m-%d').date() datetime.date(2014, 12, 4) 
like image 122
Darian Moody Avatar answered Sep 18 '22 00:09

Darian Moody


You can do that with datetime.strptime()

Example:

>>> from datetime import datetime >>> datetime.strptime('2012-02-10' , '%Y-%m-%d') datetime.datetime(2012, 2, 10, 0, 0) >>> _.isoweekday() 5 

You can find the table with all the strptime directive here.


To increment by 2 days if .isweekday() == 6, you can use timedelta():

>>> import datetime >>> date = datetime.datetime.strptime('2012-02-11' , '%Y-%m-%d') >>> if date.isoweekday() == 6: ...     date += datetime.timedelta(days=2) ...  >>> date datetime.datetime(2012, 2, 13, 0, 0) >>> date.strftime('%Y-%m-%d')   # if you want a string again '2012-02-13' 
like image 42
Rik Poggi Avatar answered Sep 18 '22 00:09

Rik Poggi


from datetime import datetime

a = datetime.strptime(f, "%Y-%m-%d")
like image 36
f p Avatar answered Sep 18 '22 00:09

f p


Use datetime.datetime.strptime:

>>> import datetime
>>> date = datetime.datetime.strptime('2012-02-10', '%Y-%m-%d')
>>> date.isoweekday()
5
like image 38
phihag Avatar answered Sep 19 '22 00:09

phihag


>>> from datetime import datetime
>>> year, month, day = map(int, my_date.split('-'))
>>> date_object = datetime(year, month, day)
like image 39
Fred Avatar answered Sep 21 '22 00:09

Fred