我正在尝试编写一个参数(对于 argparse),我正在尝试以小时或天的形式定义输入。
例如:
def setup_args():
....
parser.add_argument(
"--time",
type=str,
help="Define the time period (only hours or days). Eg. 3h or 3d"
)
def time_input(user_input):
if user_input.endswith('h'):
...
# using datetime module to forward current time X hours later
elif user_input.endswith('d'):
...
# I may specify it to a max 2 days.
# using datetime module to forward current time X days later
虽然我编写的函数有效,但我想知道是否有更好的方法来解决这个问题,或者使用 endswith
是唯一的方法吗?
最佳答案
Maya 可能适合您:
>>> maya.when("in 1H").datetime()
datetime.datetime(2018, 6, 27, 22, 16, 42, 371621, tzinfo=<UTC>)
>>> maya.when("in 1 day").datetime()
datetime.datetime(2018, 6, 28, 21, 16, 42, 371621, tzinfo=<UTC>)
您甚至可以指定任意时间值,而不仅限于几小时或几天,这会使您的应用更加灵活:
>>> maya.when("now").datetime()
datetime.datetime(2018, 6, 27, 21, 20, 7, 409348, tzinfo=<UTC>)
>>> maya.when("in 1 hour 2 minutes").datetime()
datetime.datetime(2018, 6, 27, 22, 22, 7, 825372, tzinfo=<UTC>)
附言Maya 由 dateparser 提供支持.虽然您可以直接使用 dateparser 来处理所有事情,但我认为 Maya 会更有用。
关于python - Argparse 表示时间段,以小时或天为单位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51071358/