In Python, I often want to receive the date etc. as a character string and process it, but since I google it every time, I will summarize it for myself. In my case, it is processed by selecting character string → datetime → character string.
Receives the date as a string. For example, I think there are the following cases.
It's a story of what to do if you want these one day later.
First parse the string.
import datetime
#In case of 1
date1 = '2014-10-16'
d = datetime.datetime.strptime(date1, '%Y-%m-%d')
#In case of 2
date2 = '2014/10/16 20:29:39'
d = datetime.datetime.strptime(date2, '%Y/%m/%d %H:%M:%S')
This will convert it to datetime
.
Other formats can be supported by changing the above % Y-% m-% d
.
Calculate datetime
using timedelta
.
I want one day later, so
d += datetime.timedelta(days = 1)
If you do, you will get one day later.
If you pull it without adding it, it will be one day ago, and if you change days
to hours
, you can control the time instead of the date.
Finally, return datetime
to a string.
date_stringj = d.strftime('%Y-%m-%d')
This will make it a string in the specified format.
Below is a program that puts these together, receives the date as a character string, and adds one day.
add_1day.py
#!/usr/bin/python
import datetime
date_string_input = '2014-10-31'
date_format = '%Y-%m-%d'
#String → datetime
d = datetime.datetime.strptime(date_string_input, date_format)
#datetime processing
d += datetime.timedelta(days = 1)
#datetime → string
date_string_output = d.strftime(date_format)
print date_string_output
When executed, it will be as follows.
$ python time.py
2014-11-01
Recommended Posts