Programming
python string date type-conversion
Updated Sun, 24 Jul 2022 11:07:47 GMT

Convert string into Date type on Python


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?




Solution

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'




Comments (5)

  • +0 – @user1072627: And.. did it worked? — Feb 29, 2012 at 18:21  
  • +0 – That was exactly what I did: if datetime.strptime(a, "%Y-%m-%d").isoweekday() == 6: PONTO_MOVIMENTO = a — Feb 29, 2012 at 18:26  
  • +0 – Just one more question... how can I add days to my date? For example, if isoweekdday() == 6, i need to increment the date in 2 days. Have idea how I do that? Thanks again! — Feb 29, 2012 at 18:27  
  • +0 – I found out already using timedelta. But thanks! — Feb 29, 2012 at 18:36  
  • +0 – @user1072627: Yes timdelta is the right tool. Even though you've already found it I added an example anyway. :) — Feb 29, 2012 at 18:49  


External Links

External links referenced by this document: