Unable to pass argument to the python using Optparse - python

i have written this python program. whenever i run the script using parameters like
python script.py -t It returns me current time in unixtime.
but whenever i try to pass an argument like
python script.py -c 1325058720 It says LMT is not defined. So i removed the LMT from the
LMT = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime())
Then it just skip my argument and returns the current time in Localtime.
Can someone please help me to pass an argument in the LMT and convert it to Readable time format. I need to pass an argument to it and see the output in the localtime readable format
import optparse
import re
import time
GMT = int(time.time())
AMT = 123456789
LMT = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime(LMT))
VERBOSE=False
def report(output,cmdtype="UNIX COMMAND:"):
#Notice the global statement allows input from outside of function
if VERBOSE:
print "%s: %s" % (cmdtype, output)
else:
print output
#Function to control option parsing in Python
def controller():
global VERBOSE
p = optparse.OptionParser()
p.add_option('--time', '-t', action="store_true", help='gets current time in epoch')
p.add_option('--nums', '-n', action="store_true", help='gets the some random number')
p.add_option('--conv', '-c', action="store_true", help='convert epoch to readable')
p.add_option('--verbose', '-v',
action = 'store_true',
help='prints verbosely',
default=False)
#Option Handling passes correct parameter to runBash
options, arguments = p.parse_args()
if options.verbose:
VERBOSE=True
if options.time:
value = GMT
report(value, "GMT")
elif options.nums:
value = AMT
report(value, "AMT")
elif options.conv:
value = LMT
report(value, "LMT")
else:
p.print_help()

I was wrong to access the variable outside the function which didn't clicked me.
elif options.conv:
LMT = options.conv
LMT= float(LMT)
LMT = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime(LMT))
print '%s'% LMT

The parameters you pass in are completely irrelevant. Way before optparse even tries to look at your parameters, this line is executed:
LMT = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime(LMT))
And as you point out, LMT is undefined, and will raise an error.
I have no idea what you expect LMT to be at that point. time.localtime() converts a number of seconds from epoch to localtime, since you want the current time (if I understand you) you don't need to pass in anything.
So in fact, you first say that:
python script.py -t # It returns me current time in unixtime.
This is wrong, it does not. Try it and you'll see. It gives you a NameError: name 'LMT' is not defined.

Related

Where is argument read by Python parse_args?

I want to call a Python module from the command line to convert a time in my timezone to UTC time like this:
$ dt-la-utc.py "2017-10-14 12:10:00"
When I execute the module shown below, the convert_la_utc function works correctly if I hard-code the date and time. However, I want to feed it the date and time as input on the command line. But the parse_args function isn't working. If I run the Python debugger and examine the "args" variable, there's nothing in it. What am I doing wrong?
#!/usr/bin/env python
import argparse
import datetime
from pdb import set_trace as debug
import pytz
import sys
def parse_args():
"""Parse arguments."""
parser = argparse.ArgumentParser(description="Convert LA time to UTC time.")
parser.add_argument("dt", help="LA date and time in format: YYYY-MM-DD HH:MM:SS")
args = parser.parse_args()
debug()
return args
def convert_la_utc():
"""Convert time in Los Angeles to UTC time."""
date = '2017-10-12'
time = '20:45:00'
date_time = date + ' ' + time
datetime_format = '%Y-%m-%d %H:%M:%S'
local = pytz.timezone("America/Los_Angeles")
naive = datetime.datetime.strptime(date_time, datetime_format)
local_dt = local.localize(naive, is_dst=None)
utc_dt = local_dt.astimezone(pytz.utc)
print "Datetime in Los Angeles: {0}".format(date_time)
print "UTC equivalent datetime: {0}".format(utc_dt.strftime("%Y-%m-%d %H:%M:%S"))
def main():
args = parse_args()
convert_la_utc()
if __name__ == '__main__':
sys.exit(main())
You need to further retrieve your argument, for example:
def main():
args = parse_args()
dt = args.dt
What parser.parse_args() returns is an argparse.Namespace object - you can verify it by adding print type(args) in your def main(). More explanation can be found here.

How can I run two or more tasks by using just one input statement?

I'm trying to run different commands by only using one user input, in which the program runs a specific task (in this case, Weather or Time check can be run.) and prints a message as well(Depends on the command that was run). In this sample code, I haven't tried to use loop yet to go back to the command1 input so please disregard that.
Here's for the weather:
command1 = str(input("Initiate command."))
if command1 in ('Weather', 'I need weather updates', 'Updates about the weather?', 'forecast'):
print("Give me a couple of minutes.")
My problem starts here:
if command1 in ['time', 'What is the time?','time and date please.']:
import random
import time
answers_time = [
"This is the current time:\n",
"Time right now is:\n"
]
#THIS PRINTS THE TIME
print(random.choice(answers_time) + time.strftime("%A, %B %d, %Y %I:%M:%S %p"))
When I type "Time etc." it previews the time correctly, but when I
typed in "forecast or initiate any weather command." it prints (Give
me a couple mins.) < which is correct but, it proceeds with this error
print(random.choice(answers_time) + time.strftime("%A, %B %d, %Y %I:%M:%S %p"))
NameError: name 'answers_time' is not defined
How can I stop the error from occurring? As you can see, answers_time is well defined because it is the name of the list where it gets the answers.
All code:
command1 = str(input("Initiate command."))
if command1 in ['Weather', 'I need weather updates', 'Updates about the weather?', 'forecast']:
print("Give me a couple of minutes.") (code for grabbing weather here.)
elif command1 in ['time', 'What is the time?','time and date please.']:
import random
import time
answers_time = [
"This is the current time:\n",
"Time right now is:\n"
]
print(random.choice(answers_time) + time.strftime("%A, %B %d, %Y %I:%M:%S %p"))
Your code for the second command is not indented correctly. you want something like:
if command1 in [weather commands]:
#do weather related stuff
print(weather output)
elif command1 in [time commands]:
#do time related stuff
print(time output)
But instead you have:
if command1 in [weather commands]:
#do weather related stuff
print(weather output)
elif command1 in [time commands]:
#do time related stuff
print(time output)

python datetime difference in days and hours

I want to compare two datetime instances and show the how many days and hours that differs. Now I do that with .days and it does seem to work but pylint complains about it.
Is there a better way to do it since pylint complains about it?
#!/usr/bin/python
"""A test of time differences"""
from datetime import datetime, timedelta
REF_DATE = datetime.strptime("2015-01-01", "%Y-%m-%d")
def main():
"""Main function"""
today = datetime.now()
tdiff = today - REF_DATE
print("Difference is %d days %d hours" % (tdiff.days, tdiff.seconds/3600))
main()
This is the output I get from pylint:
No config file found, using default configuration
************* Module test_timedelta
E: 12,52: Instance of 'datetime' has no 'days' member (but some types could not be inferred) (maybe-no-member)
E: 12,64: Instance of 'datetime' has no 'seconds' member (but some types could not be inferred) (maybe-no-member)
W: 4, 0: Unused import timedelta (unused-import)
...
You don't need to import the timedelta name; you can safely remove it from your import list:
from datetime import datetime
Just because subtracting datetime objects produces objects of that type does not mean you need to import the type itself.
As for the other lines, pylint simply is making a wrong inference. You can safely ignore those lines. You can disable that warning by using a comment for the print() line:
tdiff = today - REF_DATE
print("Difference is %d days %d hours" % (
tdiff.days, tdiff.seconds/3600)) #pylint: disable=E1103
You can apply the comment to the whole function too:
def main():
"""Main function"""
#pylint: disable=E1103
today = datetime.now()
tdiff = today - REF_DATE
print("Difference is %d days %d hours" % (tdiff.days, tdiff.seconds/3600))

Linking Python to AppleScript for datetime

Basically my goal is to be able to use a start and end date from Python for arguments in this AppleScript..
import commands
cmd = """osascript -e 'tell application "Calendar"
set all_calendars to title of every calendar
if "SimpleCal" is in all_calendars then
set primary_calendar to "SimpleCal"
else
create calendar with name "SimpleCal"
set primary_calendar to "SimpleCal"
end if
set start_date_mod to date %s
set end_date_mod to date "Wednesday, August 14, 2013 at 8:10:00 PM"
tell calendar primary_calendar
set new_event to make new event at end with properties {description:"Imported with App", summary:"event_type", location:"", start date: start_date_mod, end date:end_date_mod}
tell new_event
make new display alarm at end with properties {trigger interval:-5}
end tell
end tell
end tell
'""" % ("Wednesday, August 14, 2013 at 8:00:00 PM")
status = commands.getoutput(cmd)
print status
Use strftime to convert the python date into a suitable string that Applescript can coerce into a date object:
import datetime
>>> AS_DATE_FORMAT = "%A, %B %d, %Y %I:%M:%S %p"
>>> right_now = datetime.datetime.now()
>>> date_string = right_now.strftime(AS_DATE_FORMAT)
'Wednesday, August 14, 2013 11:01:10 AM'
Then, in your AppleScript section, you just add the date:
"set start_date_mod to date %s
set end_date_mod to date " + date_string

Python: timezone.localize() not working

I am having some issues getting timezone.localize() to work correctly. My goal is to grab today's date and convert it from CST to EST. Then finally format the datetime before spitting it out. I am able to format the date correctly, but the datetime is not changing from CST to EST. Additionally when I format the date I don't see the text representation of the timezone included.
Below I have listed out a simple program I created to test this out:
#! /usr/bin/python
#Test script
import threading
import datetime
import pexpect
import pxssh
import threading
from pytz import timezone
import pytz
est = timezone('US/Eastern')
curtime = est.localize(datetime.datetime.now().strftime("%a %b %d %H:%M:%S %Z %Y"))
#test time change
#curtime = datetime.datetime.now().strftime("%a %b %d %H:%M:%S %Z %Y")
class ThreadClass(threading.Thread):
def run(self):
#now = (datetime.datetime.now() + datetime.timedelta(0, 3600))
now = (datetime.datetime.now())
print "%s says Hello World at time: %s" % (self.getName(), curtime)
for i in range(3):
t = ThreadClass()
t.start()
.localize() takes a naive datetime object and interprets it as if it is in that timezone. It does not move the time to another timezone. A naive datetime object has no timezone information to be able to make that move possible.
You want to interpret now() in your local timezone instead, then use .astimezone() to interpret the datetime in another timezone:
est = timezone('US/Eastern')
cst = timezone('US/Central')
curtime = cst.localize(datetime.datetime.now())
est_curtime = curtime.astimezone(est).strftime("%a %b %d %H:%M:%S %Z %Y")
def run(self):
print("%s says Hello World at time: %s" % (self.getName(), est_curtime))
Use cst.localize to make a naive datetime into a timezone-aware datetime.
Then use astimezone to convert a timezone-aware datetime to another timezone.
import pytz
import datetime
est = pytz.timezone('US/Eastern')
cst = pytz.timezone('US/Central')
curtime = cst.localize(datetime.datetime.now())
curtime = curtime.astimezone(est)

Categories

Resources