What is the best way to schedule `whenever` task in rails in midnight usa? - ruby-on-rails-4

We have a Rails 4 application .
What is the best way to schedule whenever task in rails in midnight usa with daylight saving ?
We need to send email at 11.58pm in night of a day's report .
We are using tzinfo gem
TZInfo::Timezone.get('America/Denver').local_to_utc(Time.parse('11:58pm')).strftime('%H:%M%p')
is not sending email at the time .

This works around the timezone issue, server is at UTC and users in another time zone (with daylight saving time). define a local action and use in cronjob.
schedule.rb
require "tzinfo"
def local(time)
TZInfo::Timezone.get('America/Denver').local_to_utc(Time.parse(time))
end
every :sunday, at: local("11:58 pm") do
#your email sending task
end
hope it will help you.

Rehan's answer was SO great! In my use case I ran into an issue where the time zone conversion also changed the day of the week the task would be scheduled for.
Perhaps there is an easier way but here is what I did.
The timezone conversion we needed would only advance the weekday.
If your use case requires the weekday to be retreated then you will need to edit this, but it should be an easy fix.
def local(time, est_weekday = nil)
days = [:sunday, :monday, :tuesday, :wednesday, :thursday, :friday, :saturday, :sunday]
local_time = Time.parse(time)
utc_time = TZInfo::Timezone.get('America/New_York').local_to_utc(local_time)
utc_time_formatted = utc_time.strftime("%I:%M %p")
if est_weekday && days.include?(est_weekday.downcase.to_sym)
#extract intended wday for ruby datetime and assign
weekday_index = days.index(est_weekday.downcase.to_sym)
#get placeholder wday from desired EST day/time
temp_est_weekday_index = local_time.wday
#get placeholder wday from adjusted UTC day/time
temp_utc_weekday_index = utc_time.wday
#has the conversion to UTC advanced the wday?
weekday_advances = temp_utc_weekday_index != temp_est_weekday_index
#adjust wday index if timezone conversion has advanced weekday
weekday_index += 1 if weekday_advances
weekday = days[weekday_index]
return {time: utc_time_formatted, day: weekday || nil }
else
return utc_time_formatted
end
end

Related

How to handle datetime vlaues in python?

I have a datetime in format = '2020-05-01'. I want the output to be 2020-05-01 00:00:00.
I use this simple code to achieve this but I am missing the time part.
datetime.strptime(month, "%Y-%m-%d")
I am using python2. Does anyone have any idea on how to achieve this. This seems like a really simple problem but for some reason I am not able to achieve it.
Your one line of code already generates a datetime value which should be set to midnight (the default value for no explicit time component). If you want to view this data with its time component, then use strftime with an appropriate format mask:
month = '2020-05-01'
dt = datetime.strptime(month, "%Y-%m-%d")
dt_out = dt.strftime("%Y-%m-%d %H:%M:%S")
print(dt_out)
This prints:
2020-05-01 00:00:00
x = datetime.strptime(month, "%Y-%m-%d")
x.strftime(month, "%Y-%m-%d %H:%M:%S")
Source:
https://www.programiz.com/python-programming/datetime/strftime

AWS set date to midnight

What is the best way to initialize a Date to midnight using AWS AppSync utility.
I need to know if we have something like this
var d = (new Date()).setUTCHours(0,0,0,0)
By using $util.time.nowEpochSeconds() , I am getting the epoch time but how do i identify the time difference that i need to add to set as midnight time
AppSync doesn't offer that capability through utils only yet and this is good feedback, I'll make sure the team sees this.
In the meantime, as a workaround, you could modify the date string to achieve what you need.
#set($time = $util.time.nowFormatted("yyyy-MM-dd/HH:mm:ss/Z"))
#set ($split = $time.split("/"))
#set ($midnight = $split[0] + " 00:00:00" + $split[2])
time: $time
midnight: $midnight
midnight epoch seconds: $util.time.parseFormattedToEpochMilliSeconds($midnight, "yyyy-MM-dd HH:mm:ssZ")
will print:
time: 2019-07-15/22:33:57/+0000
midnight: 2019-07-15 00:00:00+0000
midnight epoch seconds: 1563148800000

Python - Subtracting a specific date-time from current GMT date-time

I'm trying to do some time math, but I'm not sure how I could do this. I'd like to subtract a specific date & time I have in a string (e.g.: 15:54:00 2017-5-20) from current GMT time (e.g: 20:06:27 2017-12-22).
Any thoughts on how I could do this?
# import data into Python
with open(output_file2) as f:
reader = csv.reader(f, delimiter="\t")
d = list(reader)
# here, objects [0][4] and [0][5] would be, for instance: 15:54:00 and 2017-5-20
# , respectively
# UTC Time
os.system("date -u \"+%H:%M:%S %Y-%m-%d\" | gawk '{print \" UTC Date & Time: \", $1, \"\", $2}'")
# eg.: 20:06:27 2017-12-22
Any thoughts would be great! Thanks =)
Update: I've tried so far:
UTC_time = datetime.datetime.utcnow().strftime("%H:%M:%S %Y-%m-%d")
print ' UTC Date & Time: ', UTC_time
time1 = d[0][4]
date1 = d[0][5]
mytime = time1, date1
time_difference = datetime.datetime.utcnow() - mytime
print "HELLO", time_difference
but I keep getting an error:
TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'tuple'
Not sure what I am doing wrong...
Your mytime variable is not a datetime.datetime object and cannot be used to operate against one. Instead of mytime = time1, date1 you are looking for something more along the lines of
my_date_str = "{} {}".format(time1, date1)
mytime = datetime.datetime.strptime(my_date_str, "%H:%M:%S %Y-%m-%d")
Do realize that in spite of using utcnow() the resulting datetime.datetime object is NOT timezone aware, and neither is mytime. So any math between the two is pure clock math, no timezones taken into account.
If you require timezone support, look into pytz or Pendulum or perhaps find another if they don't suit you.

How To Use The Current Local Time of Day To Control A Process Without Dates

I need to stop a process at 8:00 PM PDT everyday or as soon as possible after 8:00 PM. I see a lot about other uses of the time function but the examples all seem to be a difference in time, the timing of something, or always have the date included.
Could someone please provide an example along the lines of how I make something like this work...?
if currenttime >= 8:00 PM PDT:
time.sleep(99999999)
And also, what will I need to import, and how do I do the import?
the method I know is:
import datetime #this is the way to import a module named datetime...
import time #this module is used to sleep
a = str(datetime.datetime.now()) #a = '2016-03-27 00:20:28.107000' #for example
a = a.split(' ')[1] #get rid of the date and keep only the '00:20:28.107000' part
if a.startwith('20:00'): time.sleep(3600*12) #sleep for 12 hours (43200 seconds)
hope this helps you
edit: change timezone to pdt:
import datetime,pytz #for python_TimeZone
a = str(datetime.datetime.now(pytz.timezone('US/Pacific'))) #basically get the time in the specified zone
#from here continue as above...
taken from: http://www.saltycrane.com/blog/2009/05/converting-time-zones-datetime-objects-python/
good luck (next time try searching it in google...)
I actually ended up using a combination of hai tederry's answer and that found on http://www.saltycrane.com/blog/2008/06/how-to-get-current-date-and-time-in/
resulting in:
import time # import time library
import datetime # this is the way to import a module named datetime...
import pytz # imports Python time zone (needed to first do: sudo easy_install --pytz upgrade)
now = datetime.datetime.now(pytz.timezone('US/Pacific'))
timenow = now.strftime("%I:%M %p")
print timenow
if timenow > "08:30 PM" and timenow < "08:45 PM":
print "Programmed Pause"
time.sleep(999999)
This creates a time only output in your local 12 hour format with AM/PM that can be used in if statements, etc.

Local time using UTC, coordinates (PyEphem not working)

I have a list of coordinates and UTC time but frustratingly pyephem's localtime function doesn't work--it displays the computer's local time. I want to filter out stations that are in night time (not in between the hours of 8 am and 4 pm). Is there an easy way to do this?
for sit,lat,lon in zip(nsites,lats,longs):
user=[]
user = ephem.Observer()
user.lat = lat
user.lon = lon
user.date=bstart
if ephem.localtime(user.date).time()>=datetime.time(8) and ephem.localtime(user.date).time()<=datetime.time(16):
user.date=cend
if ephem.localtime(user.date).time()>=datetime.time(8) and ephem.localtime(user.date).time()<=datetime.time(16):
mask.append(True)
else:
mask.append(False)
else:
mask.append(False)
adding to rickhg12hs answer, consider setting user.horizon to "–6" (civil twilight), "-12" (nautical twilight), or "-18" (astronomical twilight) depending on how dark you need it to be for your use case.