我的问题是通过html解析器网站,我在格式字符串中提取时间。 我需要将字符串转换为datetime,然后转换为您的时区。
由于
hora = soup.select('span.match-time')[0].get_text().strip( ' - ' )
dt_obj = datetime.strptime(hora, '%H:%M')
print (dt_obj)
input_time = datetime.strptime(dt_obj, '%H:%M').time()
utc_dt = datetime.combine(datetime.utcnow(), input_time)
tz = pytz.timezone('America/Montevideo')
salida = str(utc_dt.replace(tzinfo=pytz.utc).astimezone(tz))
错误 /
System/Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6 /Users/fa/Desarrollo/football/parser.py
1900-01-01 19:30:00
Traceback (most recent call last):
File "/Users/fa/Desarrollo/football/parser.py", line 24, in <module>
input_time = datetime.strptime(dt_obj, '%H:%M').time()
TypeError: strptime() argument 1 must be string, not datetime.datetime
Process finished with exit code 1
答案 0 :(得分:0)
datetime.datetime.strptime接受一个你要解析时间的字符串,采用一种格式,在该格式中指定时间写入字符串的方式,然后解析字符串以提取日期时间对象
再读一遍,确保你真的得到它。它产生错误的原因现在应该是显而易见的!您正在将对象传递给需要两个字符串的函数。
一旦你把它解析为一个对象,就可以在它上面调用方法,比如下面的文字:
>>> dt_obj = datetime.datetime.strptime("12:00", "%H:%M")
>>> dt_obj
datetime.datetime(1900, 1, 1, 12, 0)
>>> dt_obj.hour
12
>>> dt_obj.minute
0
>>> dt_obj.time()
datetime.time(12, 0)
>>> dt_obj.year
1900
从我看到的,你提取小时和分钟,然后按照UTC标准继续用今天的日期/月/年构建datetime对象。我不知道你对时区做了什么,所以我会把最后两行留给你。
>>> dt_obj = datetime.strptime("12:00", "%H:%M")
>>> input_time = dt_obj.time()
>>> utc_dt = datetime.combine(datetime.utcnow(), input_time)
或者如果你需要更短
>>> dt_obj = datetime.strptime("12:00", "%H:%M")
>>> utc_dt = datetime.combine(datetime.utcnow(), dt_obj.time())
这会让您从12:00
转到datetime.datetime(2015, 2, 11, 12, 0)
答案 1 :(得分:0)
如果19:30
等输入时间字符串是指UTC时间:
#!/usr/bin/env python
from datetime import datetime
import pytz
tz = pytz.timezone('America/Montevideo')
time_string = '19:30'
utc_dt = datetime.combine(datetime.utcnow(),
datetime.strptime(time_string, '%H:%M').time())
dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(tz)
print(dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'))
# -> 2015-02-11 17:30:00 UYST-0200
如果输入时间是乌拉圭的时间:
#!/usr/bin/env python
from datetime import datetime
import pytz
tz = pytz.timezone('America/Montevideo')
time_string = '19:30'
naive_dt = datetime.combine(datetime.now(tz),
datetime.strptime(time_string, '%H:%M').time())
dt = tz.localize(naive_dt, is_dst=None)
print(dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'))
# -> 2015-02-11 19:30:00 UYST-0200
注意:结果不同。