[英]Python error: TypeError: expected string or buffer
I need your help with my code. 我需要您的代码帮助。 I have converted from time.struct_time
to datetime
object. 我已经从time.struct_time
转换为datetime
对象。 Now I would like to convert it back to time.struct_time
object after I have added to the next day date. 现在,在添加到第二天的日期之后,我想将其转换回time.struct_time
对象。
When I try this: 当我尝试这个:
half_hour_date = '23/02/2018 23:00PM'
epg_time_1 = time.strptime(half_hour_date, '%d/%m/%Y %I:%M%p')
#convert from time_struct_time object to datetime
date_format = datetime.datetime.fromtimestamp(time.mktime(epg_time_1))
half_hour = date_format + datetime.timedelta(days = self.program_day)
#convert from datetime to time_struct_time object
epg_time_1 = time.strptime(half_hour, '%d/%m/%Y %I:%M%p')
It give me an error: TypeError: expected string or buffer 它给我一个错误: TypeError:预期的字符串或缓冲区
The error are jumping on this line: 错误在此行上跳跃:
epg_time_1 = time.strptime(half_hour, '%d/%m/%Y %I:%M%p')
Here is the datetime object for half_hour
: 这是half_hour
的日期时间对象:
2018-02-23 23:00:00
Here is what I am trying to achieve: 这是我要实现的目标:
time.struct_time(tm_year=2018, tm_mon=2, tm_mday=23, tm_hour=23, tm_min=00, tm_sec=0, tm_wday=3, tm_yday=53, tm_isdst=-1)
Can you please help me how I can correct the error to allow me to convert it to time.struct_time
object? 能否请您帮我纠正错误,以便将其转换为time.struct_time
对象?
>>> import datetime
... import time
...
... fmt = '%d/%m/%Y %H:%M%p'
...
... half_hour_date = '23/02/2018 23:00PM'
...
... date_format = datetime.datetime.strptime(half_hour_date, fmt)
... half_hour = date_format + datetime.timedelta(days=2) # self.program_day)
...
... # convert from datetime to time_struct_time object
... epg_time_1 = time.struct_time(half_hour.timetuple())
>>> epg_time_1
time.struct_time(tm_year=2018, tm_mon=2, tm_mday=25, tm_hour=23, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=56, tm_isdst=-1)
There is no 23:00PM. 没有23:00 PM。 Change it to 11:00PM. 将其更改为11:00 PM。
As you mentioned, the error came out from the second line. 如您所述,错误是从第二行出来的。 When I run the first two lines with Python 3.6, the result was 当我使用Python 3.6运行前两行时,结果是
ValueError: time data '23/02/2018 23:00PM' does not match format '%d/%m/%Y %I:%M%p' ValueError:时间数据'23 / 02/2018 23:00 PM'与格式'%d /%m /%Y%I:%M%p'不匹配
It means that there is a problem in "23:00PM" so I suggested to change it to "11:00PM". 这意味着“ 23:00 PM”存在问题,因此我建议将其更改为“ 11:00 PM”。 Or you can use "%H" instead of "%I" (as Patrick Haugh suggested in the comment). 或者,您可以使用“%H”代替“%I”(如Patrick Haugh在评论中建议的那样)。
PS I could not give full answer because of mobile device. PS:由于移动设备,我无法给出完整答案。 Sorry for that. 抱歉
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.