Vignesh Sriram
Vignesh Sriram

Reputation: 11

How to pass timestamp as a command line argument in 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

Upvotes: 1

Views: 1964

Answers (1)

Pankaj Singh
Pankaj Singh

Reputation: 1178

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 

Output:

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

Upvotes: 2

Related Questions