将字符串“yyyyy -mm-dd”转换为datetime python [duplicate]

时间:2022-01-19 15:45:26

This question already has an answer here:

这个问题已经有了答案:

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".

我有来自用户的原始输入,比如“2015-01-30”……对于我正在使用的查询,日期必须作为字符串输入,如“yyyyy -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.

我希望在循环结束时将日期增加1个月。t“2015-01-30”变为“2015-02-27”(最好是下个月的最后一个工作日)。我希望有人能帮助我;我正在使用PYTHON,我想要转换到datetime的原因是我找到了一个函数来添加一个月。

Ideally my two questions to be answered are (in Python):

理想情况下,我需要回答的两个问题是(用Python):

1) how to convert string "yyyy-mm-dd" into a python datetime and convert back into string after applying a timedelta function

1)如何将字符串“yyyyy -mm-dd”转换为python datetime,并在应用timedelta函数后将其转换为string

2) AND/or how to add 1 month to string "yyyy-mm-dd"

2)和/或如何添加1个月的字符串“yyyyy -mm-dd”

4 个解决方案

#1


3  

You can use a one-liner, that takes the datetime, adds a month (using a defined function), and converts back to a string:

您可以使用一个一行程序,它使用datetime,添加一个月(使用定义的函数),然后转换回字符串:

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:

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)

#2


10  

Maybe these examples will help you get an idea:

也许这些例子可以帮助你理解:

from dateutil.relativedelta import relativedelta
import datetime

date1 = datetime.datetime.strptime("2015-01-30", "%Y-%m-%d").strftime("%d-%m-%Y")
print(date1)

today = datetime.date.today()
print(today)
addMonths = relativedelta(months=3)
future = today + addMonths
print(future) 

If you import datetime it will give you more options in managing date and time variables.
In my example above I have some example code that will show you how it works.

如果您导入datetime,它将为您提供管理日期和时间变量的更多选项。在上面的示例中,我有一些示例代码,将向您展示它是如何工作的。

It is also very usefull if you would for example would like to add a x number of days, months or years to a certain date.

它也非常有用,如果你想要增加x天,月或年到一个特定的日期。

Edit: To answer you question below this post I would suggest you to look at "calendar"

编辑:为了回答你下面的问题,我建议你看看“日历”

For example:

例如:

import calendar 
january2012 = calendar.monthrange(2002,1)
print(january2012)
february2008 = calendar.monthrange(2008,2)
print(february2008)

This return you the first workday of the month, and the number of days of the month.
With that you can calculate what was the last workday of the month.
Here is more information about it: Link
Also have a loook here, looks what you might could use: Link

这是一个月的第一个工作日,一个月的天数。这样你就可以计算出这个月的最后一个工作日是什么。这里有更多关于它的信息:Link也有一个look ok,看看你可以使用什么:Link

#3


6  

converting string 'yyyy-mm-dd' into datetime/date python

from datetime import date

date_string = '2015-01-30'
now = date(*map(int, date_string.split('-')))
# or now = datetime.strptime(date_string, '%Y-%m-%d').date()

the last business day of the next month

from datetime import timedelta

DAY = timedelta(1)
last_bday = (now.replace(day=1) + 2*31*DAY).replace(day=1) - DAY
while last_bday.weekday() > 4: # Sat, Sun
    last_bday -= DAY
print(last_bday)
# -> 2015-02-27

It doesn't take into account holidays.

它不考虑假期。

#4


0  

To convert a string of that format into a Python date object:

将该格式的字符串转换为Python日期对象:

In [1]: import datetime

In [2]: t = "2015-01-30"

In [3]: d = datetime.date(*(int(s) for s in t.split('-')))

In [4]: d
Out[4]: datetime.date(2015, 1, 30)

To move forward to the last day of next month:

到下个月的最后一天:

In [4]: d
Out[4]: datetime.date(2015, 1, 30)

In [5]: new_month = (d.month + 1) if d.month != 12 else 1

In [6]: new_year = d.year if d.month != 12 else d.year + 1

In [7]: import calendar

In [8]: new_day = calendar.monthrange(new_year, new_month)[1]

In [9]: d = d.replace(year=new_year,month=new_month,day=new_day)

In [10]: d
Out[10]: datetime.date(2015, 2, 28)

And this datetime.date object can be easily converted to a 'YYYY-MM-DD' string:

这datetime。日期对象可以很容易地转换为“YYYY-MM-DD”字符串:

In [11]: str(d)
Out[11]: '2015-02-28'

EDIT:

编辑:

To get the last business day (i.e. Monday-Friday) of the month:

获得该月最后一个工作日(即星期一至星期五):

In [8]: new_day = calendar.monthrange(new_year, new_month)[1]

In [9]: d = d.replace(year=new_year,month=new_month,day=new_day)

In [10]: day_of_the_week = d.isoweekday()

In [11]: if day_of_the_week > 5:
   ....:     adj_new_day = new_day - (day_of_the_week - 5)
   ....:     d = d.replace(day=adj_new_day)
   ....:

In [11]: d
Out[11]: datetime.date(2015, 2, 27)

#1


3  

You can use a one-liner, that takes the datetime, adds a month (using a defined function), and converts back to a string:

您可以使用一个一行程序,它使用datetime,添加一个月(使用定义的函数),然后转换回字符串:

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:

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)

#2


10  

Maybe these examples will help you get an idea:

也许这些例子可以帮助你理解:

from dateutil.relativedelta import relativedelta
import datetime

date1 = datetime.datetime.strptime("2015-01-30", "%Y-%m-%d").strftime("%d-%m-%Y")
print(date1)

today = datetime.date.today()
print(today)
addMonths = relativedelta(months=3)
future = today + addMonths
print(future) 

If you import datetime it will give you more options in managing date and time variables.
In my example above I have some example code that will show you how it works.

如果您导入datetime,它将为您提供管理日期和时间变量的更多选项。在上面的示例中,我有一些示例代码,将向您展示它是如何工作的。

It is also very usefull if you would for example would like to add a x number of days, months or years to a certain date.

它也非常有用,如果你想要增加x天,月或年到一个特定的日期。

Edit: To answer you question below this post I would suggest you to look at "calendar"

编辑:为了回答你下面的问题,我建议你看看“日历”

For example:

例如:

import calendar 
january2012 = calendar.monthrange(2002,1)
print(january2012)
february2008 = calendar.monthrange(2008,2)
print(february2008)

This return you the first workday of the month, and the number of days of the month.
With that you can calculate what was the last workday of the month.
Here is more information about it: Link
Also have a loook here, looks what you might could use: Link

这是一个月的第一个工作日,一个月的天数。这样你就可以计算出这个月的最后一个工作日是什么。这里有更多关于它的信息:Link也有一个look ok,看看你可以使用什么:Link

#3


6  

converting string 'yyyy-mm-dd' into datetime/date python

from datetime import date

date_string = '2015-01-30'
now = date(*map(int, date_string.split('-')))
# or now = datetime.strptime(date_string, '%Y-%m-%d').date()

the last business day of the next month

from datetime import timedelta

DAY = timedelta(1)
last_bday = (now.replace(day=1) + 2*31*DAY).replace(day=1) - DAY
while last_bday.weekday() > 4: # Sat, Sun
    last_bday -= DAY
print(last_bday)
# -> 2015-02-27

It doesn't take into account holidays.

它不考虑假期。

#4


0  

To convert a string of that format into a Python date object:

将该格式的字符串转换为Python日期对象:

In [1]: import datetime

In [2]: t = "2015-01-30"

In [3]: d = datetime.date(*(int(s) for s in t.split('-')))

In [4]: d
Out[4]: datetime.date(2015, 1, 30)

To move forward to the last day of next month:

到下个月的最后一天:

In [4]: d
Out[4]: datetime.date(2015, 1, 30)

In [5]: new_month = (d.month + 1) if d.month != 12 else 1

In [6]: new_year = d.year if d.month != 12 else d.year + 1

In [7]: import calendar

In [8]: new_day = calendar.monthrange(new_year, new_month)[1]

In [9]: d = d.replace(year=new_year,month=new_month,day=new_day)

In [10]: d
Out[10]: datetime.date(2015, 2, 28)

And this datetime.date object can be easily converted to a 'YYYY-MM-DD' string:

这datetime。日期对象可以很容易地转换为“YYYY-MM-DD”字符串:

In [11]: str(d)
Out[11]: '2015-02-28'

EDIT:

编辑:

To get the last business day (i.e. Monday-Friday) of the month:

获得该月最后一个工作日(即星期一至星期五):

In [8]: new_day = calendar.monthrange(new_year, new_month)[1]

In [9]: d = d.replace(year=new_year,month=new_month,day=new_day)

In [10]: day_of_the_week = d.isoweekday()

In [11]: if day_of_the_week > 5:
   ....:     adj_new_day = new_day - (day_of_the_week - 5)
   ....:     d = d.replace(day=adj_new_day)
   ....:

In [11]: d
Out[11]: datetime.date(2015, 2, 27)