I have this string '2019-01-11', in year-month-day, i want to add one day to this date, and convert it into date format in python.
i tried to convert it to date format, so that i can add one day to it by using 'timedelta' class.
date_1 = datetime.datetime.strptime('2019-01-11', "%y-%m-%d")
date_1 =date_1 + datetime.timedelta(days=1)
but i got this error line 1.
raise ValueError("time data %r does not match format %r" %
ValueError: time data '2019-01-11' does not match format '%y-%m-%d'
The format you're after is:
date_1 = datetime.strptime('2019-01-11', "%Y-%m-%d")
(upper case "Y")
A four-digit year is %Y
. See the doc: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
>>> datetime.datetime.strptime('2019-01-11', "%Y-%m-%d") + datetime.timedelta(days=1)
datetime.datetime(2019, 1, 12, 0, 0)
Note also that you have a couple of typos in your original code -- the first line has a random semicolon at the end, and the second line references date1
instead of date_1
.
For the past 5 years, I've been using pandas Timestamp and Timedelta for everything date related. Once something is in Timestamp format, it can be exported as a datetime:
In[1]: from pandas import Timestamp, Timedelta
In[2]: x=Timestamp("2022-10-31") + Timedelta(1, unit="days"))
In[3]: x=x.date()
Out[3]: datetime.date(2022, 11, 1)
And if it's kept in Timestamp format, it can be printed as a string:
In[3]: x=Timestamp("2022-10-31") + Timedelta(1, unit="days")
In[4]: f"{x:%Y-%m-%d}"
Out[4]: 2022-11-01
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.