简体   繁体   中英

Django date YYYY-MM-DD

I get date in format(YYYY-MM-DD)

Then I want to add timedelta

    mydate + timedelta(days=1)

and I get error

    coercing to Unicode: need string or buffer, datetime.timedelta found

mydate is a string. Try doing this:

from datetime import datetime
parsed_date = datetime.strptime(mydate, "%Y-%m-%d")

new_date = parsed_date + timedelta(days=1)

Data sent by the client will be sent as a Unicode and you have to parse it on server side

datetime.strptime(date, '%Y-%m-%d')

If it's part of a form, the data should be reformatted automatically when cleaned (though you might need to configure the field to accept the format you expect).

You have to convert your string date to python datetime :

>>> from datetime import datetime, timedelta
>>> dt_str = "2013/10/11"
>>> dt = datetime.strptime(dt_str, "%Y/%m/%d")
>>> new_dt = dt + timedelta(days=1)
>>> print new_dt
 datetime.datetime(2013, 10, 12, 0, 0)

If you now want to get the date as string:

>>> print new_dt.strftime("%Y/%m/%d")
 '2013/10/12'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM