我想把一个变量设置为我在库中的变量。有这样的命令吗
我试图做一个简单的时区转换器,我想检查输入变量,但我只能检查pytz列表中的变量,所以我想'自动完成'变量。我能做这个吗
import time
import pytz
country = input("enter country")
from datetime import datetime
from pytz import timezone
fmt = "%H:%M %p"
now_utc = datetime.now(timezone('UTC'))
print (now_utc.strftime(fmt))
from pytz import all_timezones
if country in all_timezones:
country = #completed country in list 'all_timezones'
timecountry = now_utc.astimezone(timezone(country))
print (timecountry.strftime(fmt))
因此,您要寻找的是一种将用户输入与
all_timezones
中的字符串匹配并查找有效时区的方法据我所知,没有内置的功能可以做到这一点,你必须自己去做
这不是一个立即的任务,因为你可能有多种选择(假设用户输入只是'欧洲'),你必须考虑到这一点
可能的方法如下:
通过列表理解,我查找
all_timezones
中包含用户输入的所有字符串。如果只有一个,则脚本将假定该脚本是正确的,并执行任务。否则,如果有多个可能性,它将打印它们(每行一个,使用for循环,但您可以只打印列表,使其在屏幕上更短),然后要求用户重写国家名称。如果没有匹配项,它只打印所有可能的。您可能会发现在命令行上看到它很难看,但是您应该了解这个想法,然后改进它如果您还想检查用户输入中的拼写错误。。。这要困难得多
相关问题 更多 >
编程相关推荐