如何在python中将时间戳作为命令行参数传递? [英] How to pass timestamp as a command line argument in python?

查看:62
本文介绍了如何在python中将时间戳作为命令行参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个运行python脚本的crontab.python脚本将时间戳记作为命令行参数.但是我无法弄清楚如何获取时间戳.

I have a crontab which runs a python script. The python script takes in timestamp as the command line argument. But I am unable to figure out how can I get the timestamp.

我尝试了这个,但这不起作用.

I tried this but this is not working.

2 * * * * python3 test.py \%Y-\%m-\%H\ \%k:\%M:\%S

推荐答案

您可以将其作为任何其他命令行参数传递并进行解析,例如

You can pass it as any other command line argument and parse it something like

import argparse
import time

def mkdate(datestr):
    return time.strptime(datestr, '%Y-%m-%d')

parser = argparse.ArgumentParser()
parser.add_argument('xDate', type=mkdate)
args = parser.parse_args()
print(args.xDate)
#YEAR
print(args.xDate[0])

$ python test.py 2018-07-14 

输出:

time.struct_time(tm_year=2018, tm_mon=7, tm_mday=14, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=195, tm_isdst=-1)
2018

这篇关于如何在python中将时间戳作为命令行参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆