Basic pyephem code - python-2.7

I have a very simple code to get the longitude of the sun but when I compare the output to Astrolog and Astrodienst its incorrect, there is a 13 minute difference. I have not added Observer as I think default is midnight GMT (which is what I want). What am I doing wrong?
import ephem
start = ephem.date('2015/01/01')
end = ephem.date('2015/12/31')
f2 = open("Sun", 'w')
while start <= end:
sun = ephem.Sun(start)
ecl = ephem.Ecliptic(sun)
f2.write(str(ephem.date(start))+' '+ str(ecl.lon) +'\n')
start+=1
f2.close()
Example of results for 2015/12/30:
code - 2015/12/30 00:00:00 277:43:36.6
Astrodienst - 7°56'39 Cap
Thanks

The reason why the 13 minute difference is because of the epoch setting, when I added
sun = ephem.Sun(start, epoch = start)
the results were the same as swiss ephemeris.

Related

Quantlib; how to use PiecewiseFlatForward

I am using the function PiecewiseFlatForward to build a curve and I am using it by setting settlementDate as an "absolute" starting date, like PiecewiseFlatForward(settlementDate, swapHelpers, Actual360()), so that the curve should be unaffected by a resetting of the Settings.instance().evaluationDate. If I change Settings.instance().evaluationDate to a date in the past with respect to the original settlementDate, the reference date of the curve stays the same, but I get an error when trying to retrieve the forward rates (unlike when using the ForwardCurve function). Here the code, where after resetting the evaluation to a past date the same forwardRate function does not work (RuntimeError: 1st iteration: failed at 1st alive instrument, pillar March 16th, 2020, maturity March 16th, 2020, reference date November 27th, 2019: 2nd leg: negative time (-0.2) given):
calendar = TARGET()
todaysDate = Date(25, November, 2019)
Settings.instance().evaluationDate = todaysDate
settlementDate = Date(27, November, 2019)
calendar = TARGET()
swaps = {
(6,Months): 0.028067,
(12,Months): 0.030768,
(18,Months): 0.029352,
(24,Months): 0.028648,
(30,Months): 0.028532,
(36,Months): 0.028480,
(42,Months): 0.028420,
(48,Months): 0.028394,
(54,Months): 0.028382,
(60,Months): 0.028387}
fixedLegFrequency = Semiannual
fixedLegDayCounter = Thirty360()
fixedLegAdjustment = Unadjusted
swapHelpers = [ SwapRateHelper(QuoteHandle(SimpleQuote(swaps[(n,unit)])),
Period(n,unit), calendar,
fixedLegFrequency, fixedLegAdjustment,
fixedLegDayCounter, USDLibor(Period(6,Months)))
for n, unit in swaps.keys() ]
depoSwapCurve = PiecewiseFlatForward(settlementDate, swapHelpers, Actual360())
dates = [ spot+Period(i*6,Months) for i in range(0, len(swaps)) ]
rates = [ depoSwapCurve.forwardRate(d, USDLibor(Period(6,Months)).maturityDate(d), Actual360(), Simple).rate()
for d in dates ]
print rates
Settings.instance().evaluationDate = Date(12, September, 2019)
rates2 = [ depoSwapCurve.forwardRate(d, USDLibor(Period(6,Months)).maturityDate(d), Actual360(), Simple).rate()
for d in dates ]
print rates2
Is there a way to use the .forwardRate function without having to care about the evaluation date when the function used to build the curve is the PiecewiseFlatForward?
Are you sure there's nothing missing in the code you posted?
After correcting for the error NameError: name 'spot' is not defined (because spot is not defined in your code) with:
spot = calendar.advance(todaysDate, 2, Days)
it seems to work fine...

Get time difference between two times in swift 3

I have 2 variables where I get 2 times from datePicker and I need to save on a variable the difference between them.
let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "HHmm"
time2 = timeFormatter.date(from: timeFormatter.string(from: datePicker.date))!
I have tried to get the timeIntervalSince1970 from both of them and them substract them and get the difference on milliseconds which I will turn back to hours and minutes, but I get a very big number which doesn't corresponds to the actual time.
let dateTest = time2.timeIntervalSince1970 - time1.timeIntervalSince1970
Then I have tried using time2.timeIntervalSince(date: time1), but again the result milliseconds are much much more than the actual time.
How I can get the correct time difference between 2 times and have the result as hours and minutes in format "0823" for 8 hours and 23 minutes?
The recommended way to do any date math is Calendar and DateComponents
let difference = Calendar.current.dateComponents([.hour, .minute], from: time1, to: time2)
let formattedString = String(format: "%02ld%02ld", difference.hour!, difference.minute!)
print(formattedString)
The format %02ld adds the padding zero.
If you need a standard format with a colon between hours and minutes DateComponentsFormatter() could be a more convenient way
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute]
print(formatter.string(from: time1, to: time2)!)
TimeInterval measures seconds, not milliseconds:
let date1 = Date()
let date2 = Date(timeIntervalSinceNow: 12600) // 3:30
let diff = Int(date2.timeIntervalSince1970 - date1.timeIntervalSince1970)
let hours = diff / 3600
let minutes = (diff - hours * 3600) / 60
To get duration in seconds between two time intervals, this can be used -
let time1 = Date(timeIntervalSince1970: startTime)
let time2 = Date(timeIntervalSince1970: endTime)
let difference = Calendar.current.dateComponents([.second], from: time1, to: time2)
let duration = difference.second
Now you can do it in swift 5 this way,
func getDateDiff(start: Date, end: Date) -> Int {
let calendar = Calendar.current
let dateComponents = calendar.dateComponents([Calendar.Component.second], from: start, to: end)
let seconds = dateComponents.second
return Int(seconds!)
}

How to put colon inbetween elements of a big number using python

My question is my title . I want to put colon to number 2034820. It should look like 2:03:48:20
Basically this is my time data in HHMMSSMS format i.e hour minute second and millisecond.I want to plot other data with respect to this time format. How can I plot my data in y-axis and time of given format in x-axis.
data = numpy.genfromtxt('inputfile.dat') fig=plt.figure()
ax1 = plt.subplot(111) sat1=ax1.plot(data[:,1],'b',linewidth=1,label='SVID-127')
sat2 = ax1.plot(data[:,2],'m-',linewidth=1,label='SVID-128')
Any help is highly appreciated.
Thanks
you can parse the time with datetime.strptime and then re-format it:
from datetime import datetime
tme = datetime.strptime('{:08d}'.format(2034820), '%H%M%S%f').time()
strg = '{0:%H:%M:%S:%f}'.format(tme)
print(strg[:-4]) # cut the trailing '0000'
# 02:03:48:20
this assumes your input is an integer (which will be converted to a zero-padded string of length 8 with '{:08d}'.format(2034820); if the data comes as string you need to convert it to an int first: '{:08d}'.format(int('2034820'))).
from your comments: you seem to be getting the number of seconds that have passed since midnight. for those you could to this:
from datetime import time
def convert(timefloat):
hours, rest = divmod(timefloat, 3600)
mins, rest = divmod(rest, 60)
secs, rest = divmod(rest, 1)
microsecs = int(10**6 * rest)
tme = time(int(hours), int(mins), int(secs), microsecs)
return '{0:%H:%M:%S:%f}'.format(tme)[:-4]
which gives for your test-data:
for d in data:
print(convert(d))
#23:59:59:58
#23:59:59:80
#23:59:59:99
#00:00:00:20
#00:00:00:40
#00:00:00:60

Extracting integers from strings

I need some help extracting an integer from strings created by beautiful soup. This is the following code I have.
# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
#San Pedro
url = "http://www.ndbc.noaa.gov/mobile/station.php?station=46222"
r = requests.get(url)
soup = BeautifulSoup(r.content, "html.parser")
g_data = soup.find_all("body")
for item in g_data:
#Wheater Conditions
print item.contents[6]
#Wave Summary
print item.contents[9]
I am given the following output.
9:19 pm PST 01-Dec-2015
Seas: 3.9 ft (1.2 m)
Peak Period: 15 sec
Water Temp: 65 °F (18 °C)
9:19 pm PST 01-Dec-2015
Swell: 3.0 ft (0.9 m)
Period: 15.4 sec
Direction: W
Wind Wave: 2.3 ft (0.7 m)
Period: 9.9 sec
Direction: W
HTML Version
<p>9:19 pm PST 01-Dec-2015<br>
<b>Seas:</b> 3.9 ft (1.2 m)<br>
<b>Peak Period:</b> 15 sec<br>
<b>Water Temp:</b> 65 °F (18 °C)<br>
</br></br></br></br></p>
<p>
9:19 pm PST 01-Dec-2015<br>
<b>Swell:</b> 3.0 ft (0.9 m)<br>
<b>Period:</b> 15.4 sec<br>
<b>Direction:</b> W<br>
<b>Wind Wave:</b> 2.3 ft (0.7 m)<br>
<b>Period:</b> 9.9 sec<br>
<b>Direction:</b> W<br>
</br></br></br></br></br></br></br></p>
I need to get the individual value of each category I.E. make a value as such swell = 3.0
Thanks
Not sur this is the best solution but something like this should do :
def extractInt(string) :
stringToReturn = ""
for x in string :
if x.isdigit() or x==" " :
stringToReturn = stringToReturn + x
return stringToReturn
Just call this function on the string you want.
If you want to have numbers with floating points, you want to have floats intead of integers. To simply get number from string do:
if your_string.isdigit():
your_float = float(your_string)

isDst in Time Zone in C language

I am trying to figure out on making a time from the values i choose (dynamically)
I tried giving a date of 31st march 03:10pm and trying to go back a month with 03:10Pm which is 28th Feb 03:10Pm. But i am getting a value as 04:10Pm.
I set the isdst = -1 to do this bit; but still it fails.
Any ideas.
Tm->tm_mon = ReportMonth;
Tm->tm_mday = ReportEndDay;
Tm->tm_hour = TimeOfDay/60;
Tm->tm_min = TimeOfDay%60;
Tm->tm_sec = 59;
Tm->tm_isdst = -1;