Python自定义datetime(?)格式处理 [英] Python custom datetime(?) format handling
问题描述
例如'52300',这意味着第五天(星期五) ,23小时00分钟。
如何解析它到time或datetime对象来添加timedelta(小时= 3),并将其恢复到这种奇怪的格式?
我尝试过:
tow_str ='52300'
tow = datetime.datetime.strptime(tow_str,%w%H%M)+ datetime.timedelta(hours = 3)
print(tow.strftime(% w%H%M))
返回'20200'而不是'60200'
正确地解析日期与%w
要求您包括日期本身,否则日期设置为1900-01-01:
>>> import datetime
>>>> tow_str ='52300'
>>>> datetime.datetime.strptime(tow_str,%w%H%M)
datetime.datetime(1900,1,1,23,0)
,当您格式化为字符串时,您总是会收到 1
:
>>> datetime.datetime.strptime(tow_str,%w%H%M)strftime(%w%H%M)
'12300'
没有日期,%w
是无意义的。
您可以根据今天的日期从工作日产生一个日期,只能解析时间:
def nearest_date_for_weekday(weekday) :
today = datetime.date.today()
返回今天+ datetime.timedelta(days = weekday - today.weekday())
parsed_date = datetime.datetime.combine (
nearest_date_for_weekday(int(tow_str [0])),
datetime.datetime.strptime(tow_str [1:],'%H%M')time())
print parsed_date.strftime('%w%H%M')
所以这产生一个完整的 datetime
对象,因此格式化回到一个字符串给出了一个有意义的值%w
。
Let's say i have a string representing a time with number of day of the week:
For example '52300', which means 5th day of week(Friday), 23 Hours 00 Minutes.
How do i parse it to time or datetime object to add a timedelta(hours=3) and get it back to this strange format? Expected output is '60200' string.
I have tried:
tow_str = '52300'
tow = datetime.datetime.strptime(tow_str, "%w%H%M") + datetime.timedelta(hours=3)
print(tow.strftime("%w%H%M"))
which returns '20200' instead of '60200'
Parsing a date with %w
accurately requires that you include the date itself, otherwise the date is set to 1900-01-01:
>>> import datetime
>>> tow_str = '52300'
>>> datetime.datetime.strptime(tow_str, "%w%H%M")
datetime.datetime(1900, 1, 1, 23, 0)
and you always end up with 1
when formatting back to a string:
>>> datetime.datetime.strptime(tow_str, "%w%H%M").strftime("%w%H%M")
'12300'
Without a date, %w
is meaningless.
You could produce a date from the weekday based on today's date, and only parse the time:
def nearest_date_for_weekday(weekday):
today = datetime.date.today()
return today + datetime.timedelta(days=weekday - today.weekday())
parsed_date = datetime.datetime.combine(
nearest_date_for_weekday(int(tow_str[0])),
datetime.datetime.strptime(tow_str[1:], '%H%M').time())
print parsed_date.strftime('%w%H%M')
So this produces a complete datetime
object, so formatting back to a string gives a meaningful value for %w
.
这篇关于Python自定义datetime(?)格式处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!