我想将字符串转换为datetime对象。我的代码运行良好:
from datetime import datetime, timedelta
time_str_now = str(input('Ingresar hora: '))
time_format = '%H:%M:%S'
time_now = datetime.strptime(time_str_now, time_format)
time_plus = int(input('Ingresar hora adicional: '))
time_from_now = time_now + timedelta(minutes = time_plus)
fecha_hora = '{:%H:%M:%S}'.format(time_from_now)
print(fecha_hora)
打印:
Ingresar hora: 00:00:00
Ingresar hora adicional: 45
00:45:00
现在,我想提供一个选项来选择用户是否需要"小时","分钟","秒"或"毫秒"。我试过这个:
from datetime import datetime, timedelta
time_str_now = str(input('Ingresar hora: '))
time_format = '%H:%M:%S'
time_now = datetime.strptime(time_str_now, time_format)
time_plus = int(input('Ingresar hora adicional: '))
operador = str(input('Oparador: ')) #here is where the user shuld to select the input: hours, minutes, seconds, ...
time_from_now = time_now + timedelta(operador = time_plus) #here is where it should go: hours, minutes, seconds, ...
fecha_hora = '{:%H:%M:%S}'.format(time_from_now)
print(fecha_hora)
但我得到以下例外:
Traceback (most recent call last):
File "C:/Users/Tatiana/Documents/Python Projects/Pruebas1.py", line 10, in <module>
time_from_now = time_now + timedelta(operador = time_plus)
TypeError: 'operador' is an invalid keyword argument for this function
答案 0 :(得分:2)
如果要将成员参数化为递增,则必须解压缩一个参数dict哪个键应该是kwarg到timedelta函数
>>> from datetime import datetime,timedelta
>>> op='days'
>>> increment_value=1
>>> dt_now = datetime.now()
>>> dt_now + timedelta(**{op:increment_value})
datetime.datetime(2014, 8, 15, 7, 40, 15, 519452)
此片段相当于
>>> dt_now + timedelta(days = 1)
这是因为dict将被解压缩并且每个项目将被翻译为timedelta函数的关键字参数