localtime not actually giving localtime - python-3.x

there's obviously a time module that works in combination with this problem, but I have not found it yet.
I'm simply trying to use Pyephem on a Raspberry Pi to find out what time sunrise and sunset is for my latitude longitude coordinates.
the code is quite simply this:
import ephem
import datetime
import time
now = datetime.datetime.now()
gmNow = time.mktime(time.localtime())
Vancouver = ephem.Observer()
Vancouver.lat = 49.2878
Vancouver.horizon = 0
Vancouver.lon = -123.0502
Vancouver.elevation = 80
Vancouver.date = now
# Vancouver.date = time.localtime()
sun = ephem.Sun()
print("sunrise is at",ephem.localtime(Vancouver.next_rising(sun)))
print("sunset is going to be at ",ephem.localtime(Vancouver.next_setting(sun)))
print("now is ",now)
print("gmNow is",gmNow)
what exports, when that runs is wrong by 8 hours though. so it appears that the
ephem.localtime() is not actually running.
pi#raspberrypi ~ $ sudo python3 vivarium_sun.py
sunrise is at 2014-09-19 12:55:56.000004
sunset is going to be at 2014-09-19 00:52:30.000004
now is 2014-09-19 06:22:24.014859
gmNow is 1411132944.0
It's driving me nuts, and it's obviously one of those simple things once it's figured out, so I'm going to the hive mind here.
EDIT** Just typing 'date' into the command line of the Raspberry Pi returns the following:
pi#raspberrypi ~ $ date
Fri Sep 19 18:41:42 PDT 2014
which is accurate.

You should pass datetime.utcnow() to the observer instead of your local time.
ephem expects latitude and longitude in radians if passed as floats, use strings instead:
from datetime import datetime, timezone
import ephem
now = datetime.now(timezone.utc)
Vancouver = ephem.Observer()
Vancouver.lat = '49.2878'
Vancouver.horizon = 0
Vancouver.lon = '-123.0502'
Vancouver.elevation = 80
Vancouver.date = now
sun = ephem.Sun(Vancouver)
print("sunrise is at", ephem.localtime(Vancouver.next_rising(sun)))
print("sunset is going to be at ",
ephem.localtime(Vancouver.next_setting(sun)))
print("now is ",now.astimezone())
Output
sunrise is at 2014-09-20 06:55:38.000005
sunset is going to be at 2014-09-19 19:16:38.000004
now is 2014-09-19 19:15:04.171486-07:00

Related

converting time from UTC to CST

I am trying to convert UTC time to CST. But I am not getting the output as expected.
Below is my code:
import datetime
import pytz
fmt = '%Y-%m-%d %H:%M:%S %Z%z'
e = pytz.timezone('US/Central')
time_from_utc = datetime.datetime.utcfromtimestamp(int(1607020200))
time_from = time_from_utc.astimezone(e)
time_from.strftime(fmt)
time_to_utc = datetime.datetime.utcfromtimestamp(int(1609785000))
time_to = time_to_utc.astimezone(tz=pytz.timezone('US/Central'))
print(time_from_utc)
print(time_from)
print(time_to_utc)
print(time_to)
Here is the output:
(base) ranjeet#casper:~/Desktop$ python3 ext.py
2020-12-03 18:30:00
2020-12-03 07:00:00-06:00
2021-01-04 18:30:00
2021-01-04 07:00:00-06:00
I was expecting that after conversion, I should get time corresponding to the time of UTC i.e.
2020-12-03 18:30:00
2020-12-03 12:30:00-06:00
since CST is -6 Hours from UTC.
Any help is appreciated.
the problem is that
time_from_utc = datetime.datetime.utcfromtimestamp(int(1607020200))
gives you a naive datetime object - which Python treats as local time by default. Then, in
time_from = time_from_utc.astimezone(e)
things go wrong since time_from_utc is treated as local time. Instead, set UTC explicitly when calling fromtimestamp:
from datetime import datetime, timezone
import pytz
fmt = '%Y-%m-%d %H:%M:%S %Z%z'
e = pytz.timezone('US/Central')
time_from_utc = datetime.fromtimestamp(1607020200, tz=timezone.utc)
time_from = time_from_utc.astimezone(e)
time_from.strftime(fmt)
time_to_utc = datetime.fromtimestamp(1609785000, tz=timezone.utc)
time_to = time_to_utc.astimezone(tz=pytz.timezone('US/Central'))
which will give you
2020-12-03 18:30:00+00:00
2020-12-03 12:30:00-06:00
2021-01-04 18:30:00+00:00
2021-01-04 12:30:00-06:00
Final Remarks: with Python 3.9, you have zoneinfo, so you don't need a third party library for handling of time zones. Example usage.

How can I Change the TimeZone in my Python enviornment

Im building a bots for some clients but want the bots to activate at the same time based on Eastern time only, since Im in New York, and thats the only time I do know by heart. I don't know what timezone any of my future clients will be in so I'd rather permanently set it contingent upon eastern time. I want them all to be timed to start at 11:00AM EST - US/Eastern
from pytz import timezone
import time, datetime
def Schedule():
tz = timezone('US/Eastern')
today = datetime.datetime.now(tz)
#today = datetime.datetime.now()
Activate = (datetime.datetime(today.year, today.month, today.day, 0, 50, 0) - today).seconds
#Uses Military Time 23, 25, 0 = 11:25:00PM
print('Waiting for ' + str(datetime.timedelta(seconds=Activate)))
time.sleep(Activate)
#Rest of the code will activate at the correct time that you set it
Schedule() #Uncomment this

Write date and variable to file

I am trying to write a variable and the date and time on the same line to a file, which will simulate a log file.
Example: July 25 2018 6:00 pm - Variable contents here
So far I am able to write the variable to the file but I am unsure how to use the datetime library or other similar libraries. Some guidance would be appreciated.
Below is the current script.
import subprocess
import datetime
var = "test"
with open('auditlog.txt', 'a') as logfile:
logfile.write(var + "\n")
The fastest way I found is doing something like this:
import time
var = time.asctime()
print(var)
Result: Thu Jul 26 00:46:04 2018
If you want to change the placements of y/m/d etc. you can alternatively use this:
import time
var = time.strftime("%B %d %Y %H:%M pm", time.localtime())
print(var)
Result: July 26 2018 00:50 pm
Have a look here.
By the way, is the subprocess intended in your code? You don't need it to open/write to files. Also you should do logfile.close() in your code after you wrote to it.

Stop time from saying 07 minutes and just 7 in Pyttsx3

import pyttsx3
import time
time = time.strftime("%M minutes past %I")
engine = pyttsx3.init()
engine.setProperty('rate',200)
engine.say("Hi Tom");
engine.say("The time is" + time);
engine.runAndWait();
When running this it will say "Hi Tom, the time is 07 minutes past 10" for example and will say a 0 in front of the minutes if its between 0-9 but 10-59 its says it normally. Is there a way to remove the 0 from being said?
Could this be useful
t = time.localtime()
...
engine.say('The time is %d minutes past %s' % (t.tm_min,t.tm_hour))

How to communicate through a serial port with python?

I am creating a Solar Array Simulator with python to simulate the voltage and current being created with different angles and intensities of sunlight as a satellite orbits around the earth. I have a very simple program that outputs the voltage and current just with the angle (no orbiting parameters yet). However, I need it to communicate the outputs generated with a E4350B model solar array simulator through a serial port, and I don't know where to start. I have installed pip and used that to install PySerial but do not know what to do from there. How do I communicate the voltage and amp outputs to the simulator through COM ports? Here is what I have for my program that runs the simulator.
from math import sin,radians,pi
import time
'''Needed information:
Voc (per one cell) = 2,680mV
Vmp (per one cell = 2,325mV
Isc (per one cell) = 453mA
Imp (per one cell) = 434mA
angular velocity = .05d/s'''
#Timer eclipse set for total eclipse tim ein seconds
timeEclipse = 1800
#total eclipse time = 30 mins
#Timer sun set for how many seconds it takes to change one degree
timeSun = 20
#Total sun exposer time = 60 mins
#Find the Vmp, Voc, Imp, and Isc from Beta angles 0 - 180
def Exposure():
tSun = timeSun
for x in range(0,181):
angle = sin(radians(x))
Voc = 2680 * angle
Vmp = 2325 * angle
#Amps are going to be a function of voltage
Isc = 453 * angle
Imp = 434 * angle
#
print('At angle ',x,' Vmp = ',Vmp,
'mV, Voc = ',Voc,'mV, Isc = ',Isc,'mA, and Imp = ',Imp,'mA')
time.sleep(tSun)
#Simulate time during eclipse
#Outputs nothing
def Eclipse():
tEclipse = timeEclipse
time.sleep(tEclipse)
#Run loop through Exposure and eclipse
def Run():
run = True
while(run):
Exposure()
Eclipse()
P.S. For anybody who dabbles in a little bit of physics, I need a way to find the current as a function of the voltage at every angle.

Resources