将字符串'yyyy-mm-dd'转换为datetime python [英] converting string 'yyyy-mm-dd' into datetime python
问题描述
我有一个来自用户的原始输入,例如2015-01-30...对于我正在使用的查询,日期必须作为字符串输入yyyy-mm-dd。 / p>
我想在我的循环结束时增加1个月的日期2015-01-30成为2015-02-27(理想情况下是最后一个业务下个月的一天)。我希望有人能帮助我;我正在使用PYTHON,我想转换为datetime的原因是找到一个添加1个月的功能。
理想情况下,我要解答的两个问题是(在Python中) :
1)如何将字符串yyyy-mm-dd转换为python datetime,并在应用timedelta函数后转换为字符串
2)和/或如何添加1个月到字符串yyyy-mm-dd
p>你可以使用一个单行,它采用 datetime
,添加一个月(使用定义的函数),并转换回一个字符串:
x = add_months(datetime.datetime(* [int(item)for x.split(' - ')]),1)。 strftime(%Y-%m-%d)
>>>导入日期时间,日历
>>> x =2015-01-30
>>>> x = add_months(datetime.datetime(* [int(item)for x.split(' - ')]),1).strftime(%Y-%m-%d)
> >> x
'2015-02-28'
>>>
add_months
:
def add_months(sourcedate,months):
month = sourcedate.month - 1 + months
year = sourcedate.year + month / 12
month = month%12 + 1
day = min(sourcedate.day,calendar.monthrange(year,month)[1])$ b $ b return datetime.date(year,month,天)
I have a raw input from the user such as "2015-01-30"...for the query I am using, the date has to be inputed as a string as such "yyyy-mm-dd".
I would like to increment the date by 1 month at end of my loop s.t "2015-01-30" becomes "2015-02-27" (ideally the last business day of the next month). I was hoping someone could help me; I am using PYTHON, the reason I want to convert to datetime is I found a function to add 1 month.
Ideally my two questions to be answered are (in Python):
1) how to convert string "yyyy-mm-dd" into a python datetime and convert back into string after applying a timedelta function
2) AND/or how to add 1 month to string "yyyy-mm-dd"
You can use a one-liner, that takes the datetime
, adds a month (using a defined function), and converts back to a string:
x = add_months(datetime.datetime(*[int(item) for item in x.split('-')]), 1).strftime("%Y-%m-%d")
>>> import datetime, calendar
>>> x = "2015-01-30"
>>> x = add_months(datetime.datetime(*[int(item) for item in x.split('-')]), 1).strftime("%Y-%m-%d")
>>> x
'2015-02-28'
>>>
add_months
:
def add_months(sourcedate,months):
month = sourcedate.month - 1 + months
year = sourcedate.year + month / 12
month = month % 12 + 1
day = min(sourcedate.day,calendar.monthrange(year,month)[1])
return datetime.date(year,month,day)
这篇关于将字符串'yyyy-mm-dd'转换为datetime python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!