How to convert a string to datetime.timedelta ()?

how can i convert my date string to datetime.timedelta () in python?

I have this code:

import datetime date_select = '2011-12-1' delta = datetime.timedelta(days=1) target_date = date_select + delta print target_date 

thanks in advance...

+4
source share
2 answers

You would not convert date_select to timedelta , instead you need a datetime object that you can add to timedelta to create an updated datetime object:

 from datetime import datetime, timedelta date_select = datetime.strptime('2011-12-1', '%Y-%m-%d') delta = timedelta(days=1) target_date = date_select + delta print target_date 

Or, if you want, without the fantastic line from ... import ... import:

 import datetime # <- LOOK HERE, same as in your example date_select = datetime.datetime.strptime('2011-12-1', '%Y-%m-%d') delta = datetime.timedelta(days=1) target_date = date_select + delta print target_date 
+9
source

For this, strptime used.

 from datetime import datetime target_date = datetime.strptime(date_select, '%Y-%m-%d') 
0
source

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


All Articles