Linking Python to AppleScript for datetime - python

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

Related

Create a function which returns french date or english date

I have created a function language which returns English or French. I would like to create a function that would give the date now based on a select language. For instance, if I select French, the function will return Jeudi, 28 mars 2017 or if I select English, it will return Tuesday March 28 2017.
#property
def date_customerprofile(self):
now = datetime.date.today()
if language == 'English'
date = now.strftime("%A, %B %d %Y")
else:
date = ...
Could anyone be able to help me to finish this function to get such results?
Thanks!
P.S. Knowing that months in French are Janvier, Février, Mars, Avril, Mai, Juin, Juillet, Août, Septembre, Octobre, Novembre and Décembre. Days of week are Dimanche (Sunday), Lundi, Mardi, Mercredi, Jeudi, Vendredi and Samedi
First you need to have required locale installed on your system.
For ubuntu to install french locale, run below command.
$ sudo locale-gen fr_FR.utf8
Below is the solution for the question
from datetime import datetime
import locale
def set_locale(locale_):
locale.setlocale(category=locale.LC_ALL, locale=locale_)
def date_customerprofile(language):
now_ = datetime.today()
if language == 'English':
set_locale('en_US.utf8')
date_ = now_.strftime("%A %B %d %Y")
else:
set_locale('fr_FR.utf8')
date_ = now_.strftime("%A %B %d %Y")
return date_
P.S. Avoid using standard package/function names as variables

Execute command in time increments of 1 second on same line in terminal

This script I have is very simple. Until the script is manually stopped, it prints, in the terminal, the current time every 1 second. The only problem I've had thus far is the carriage return '\r' command used to go back and use the same line as before does not work as intended. Instead of the time being overwritten each time, I get an output like this:
Good morning!
It's 03:10:13 PM on Wednesday, Jan 25, 2017
It's 03:10:14 PM on Wednesday, Jan 25, 2017
It's 03:10:15 PM on Wednesday, Jan 25, 2017
It's 03:10:16 PM on Wednesday, Jan 25, 2017
It's 03:10:17 PM on Wednesday, Jan 25, 2017
It's 03:10:18 PM on Wednesday, Jan 25, 2017
It's 03:10:19 PM on Wednesday, Jan 25, 2017
It's 03:10:20 PM on Wednesday, Jan 25, 2017
It's 03:10:21 PM on Wednesday, Jan 25, 2017
Am I not allowed to do this on terminal? Is there a problem with the 1 second pause I'm putting in between?
Here is my code:
import time
import sys
print("Good morning!")
while True:
time_str = "It's %I:%M:%S %p on %A, %b %d, %Y\r"
print time.strftime(time_str)
sys.stdout.flush()
time.sleep(1)
Some extra information: I'm using a bash shell on an Ubuntu system
You have to use end="\r" in print() to replace default end="\n"
import time
import sys
print("Good morning!")
while True:
time_str = "It's %I:%M:%S %p on %A, %b %d, %Y"
print(time.strftime(time_str), end="\r")
sys.stdout.flush()
time.sleep(1)
I use Linux Mint (based on Ubuntu) and \r works for me in terminal (but maybe Ubuntu use different terminal).
You get error with end="\r" so this means that you use Python 2, not Pyhton 3 - and then you need comma at the end in print to skip default \n
import time
import sys
print "Good morning!"
while True:
time_str = "It's %I:%M:%S %p on %A, %b %d, %Y\r"
print time.strftime(time_str), # <-- comma to skip "\n"
sys.stdout.flush()
time.sleep(1)
You must place the carriage return at the beginning of the text and replace the carriage end with ""
import time
import sys
print("Good morning!")
while True:
time_str = "\rIt's %I:%M:%S %p on %A, %b %d, %Y"
print(time.strftime(time_str), end="")
sys.stdout.flush()
time.sleep(1)

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)

Unable to pass argument to the python using Optparse

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.

Regular expression replace function includes too much text

I'm a python newbie. My script (below) contains a function named
"fn_regex_raw_date_string" that is intended to convert
a "raw" date string like this: Mon, Oct 31, 2011 at 8:15 PM
into a date string like this: _2011-Oct-31_PM_8-15_
Question No. 1: When the "raw" date string contains extraneous
characters eg (xxxxxMon, Oct 31, 2011 at 8:15 PMyyyyyy), how should
I modify my regular expression routine to exclude the extraneous characters?
I was tempted to remove my comments from the script below to make it
simpler to read, but I thought it might be more helpful for me to leave
them in the script.
Question No. 2: I suspect that I should code another function that will
replace the "Oct" in "2011-Oct-31_PM_8-15_ " with "11". But I can't
help wondering if there is some way to include that functionality in
my fn_regex_raw_date_string function.
Any help would be much appreciated.
Thank you,
Marceepoo
import sys
import re, pdb
#pdb.set_trace()
def fn_get_datestring_sysarg():
this_scriptz_FULLName = sys.argv[0]
try:
date_string_raw = sys.argv[1]
#except Exception, e:
except Exception:
date_string_raw_error = this_scriptz_FULLName + ': sys.argv[1] error: No command line argument supplied'
print date_string_raw_error
#returnval = this_scriptz_FULLName + '\n' + date_string_raw
returnval = date_string_raw
return returnval
def fn_regex_raw_date_string(date_string_raw):
# Do re replacements
# p:\Data\VB\Python_MarcsPrgs\Python_ItWorks\FixCodeFromLegislaturezCalifCode_MikezCode.py
# see also (fnmatch) p:\Data\VB\Python_MarcsPrgs\Python_ItWorks\bookmarkPDFs.aab.py
#srchstring = r"(.?+)(Sun|Mon|Tue|Wed|Thu|Fri|Sat)(, )(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)( )([\d]{1,2})(, )([\d]{4})( at )([\d]{1,2})(\:)([\d]{1,2})( )(A|P)(M)(.?+)"
srchstring = r"(Sun|Mon|Tue|Wed|Thu|Fri|Sat)(, )(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)( )([\d]{1,2})(, )([\d]{4})( at )([\d]{1,2})(\:)([\d]{1,2})( )(A|P)(M)"
srchstring = re.compile(srchstring)
replacement = r"_\7-\3-\5_\13M_\9-\11_"
#replacement = r"_\8-\4-\6_\14M_\10-\12_"
regex_raw_date_string = srchstring.sub(replacement, date_string_raw)
return regex_raw_date_string
# Mon, Oct 31, 2011 at 8:15 PM
if __name__ == '__main__':
try:
this_scriptz_FULLName = sys.argv[0]
date_string_raw = fn_get_datestring_sysarg()
date_string_mbh = fn_regex_raw_date_string(date_string_raw)
print date_string_mbh
except:
print 'error occurred - fn_get_datestring_sysarg()'
You probably want to use python's standard datetime stuff:
http://docs.python.org/library/time.html#time.strptime
http://mail.python.org/pipermail/tutor/2006-March/045729.html
This code uses a regular expression that replaces everything at the start of a string before an abbreviated weekday is matched, and then everything to the end of the string after matching either AM or PM.
Then it calls datetime.strptime(date_str, date_format) which does the hard work of parsing and gives us a datetime instance:
from datetime import datetime
import calendar
import re
# -------------------------------------
# _months = "|".join(calendar.month_abbr[1:])
_weekdays = "|".join(calendar.day_abbr)
_clean_regex = re.compile(r"""
^
.*?
(?=""" + _weekdays + """)
|
(?<=AM|PM)
.*?
$
""", re.X)
# -------------------------------------
def parseRawDateString(raw_date_str):
try:
date_str = _clean_regex.sub("", raw_date_str)
return datetime.strptime(date_str, "%a, %b %d, %Y at %I:%M %p")
except ValueError as ex:
print("Error parsing date from '{}'!".format(raw_date_str))
raise ex
# -------------------------------------
if __name__ == "__main__":
from sys import argv
s = argv[1] if len(argv) > 1 else "xxxxxMon, Oct 31, 2011 at 8:15 PMyyyyyy"
print("Raw date: '{}'".format(s))
d = parseRawDateString(s)
print("datetime object:")
print(d)
print("Formatted date: '{}'".format(d.strftime("%A, %d %B %Y # %I:%M %p")))

Categories

Resources