Darksky Loop through one year of daily data - Datetime Error - python

I attempt to loop through daily weather data in 2019 using forecastiopy but the error keeps showing. Not sure what the problem is.
import pandas as pd
import requests
import json
from forecastiopy import *
from datetime import date, timedelta, datetime
import datetime
key = 'xxxxx'
city = [40.730610, -73.935242]
start = datetime.datetime(2019, 1, 1)
for day in range(1,365):
fio = ForecastIO.ForecastIO(key,
units=ForecastIO.ForecastIO.UNITS_SI,
lang=ForecastIO.ForecastIO.LANG_ENGLISH,
latitude=city[0],
longitude=city[1],
time=start+datetime.timedelta(day))
daily = FIODaily.FIODaily(fio)
print ('Max Temperature', daily.get_day(day)['temperatureMax'])
print ('Min Temperature:', daily.get_day(day)['temperatureMin'])
print ('Precipitation Pobability:', daily.get_day(day)['precipProbability'])
print ('Precipitation Intensity', daily.get_day(day)['precipIntensity'])
The error shown is below.

ForecastIO.ForecastIO(key,
...,
time=start+datetime.timedelta(day))
Here, the time argument is supposed to be a string that is directly mapped to the Dark Sky API:
time
Either be a UNIX time (that is, seconds since midnight
GMT on 1 Jan 1970) or a string formatted as follows:
[YYYY]-[MM]-[DD]T[HH]:[MM]:[SS][timezone]. [...]
Therefore, you could format the datetime object using isoformat()
ForecastIO.ForecastIO(key,
...,
time=(start+datetime.timedelta(day)).isoformat())

Related

How to get correct date instead of system date in python

I'm working on a project, there's one problem, I need to fetch a correct date. and I can also fetch date from web --> Python Getting date online? , but the date will not be correct for every single person, Like if someone is living in USA so that's a problem, So how can I implement to fetch correct time for everyone.
THANKS
import requests
import datetime
import time
r = requests.get('http://just-the-time.appspot.com/')
utc_current_time = datetime.datetime.strptime(r.content.decode().strip(), '%Y-%m-%d %H:%M:%S')
print(f'utc_current_time: {utc_current_time}')
utc_offset_in_seconds = time.timezone
if(utc_offset_in_seconds > 0):
local_time = utc_current_time - datetime.timedelta(seconds=abs(time.timezone))
else:
local_time = utc_current_time + datetime.timedelta(seconds=abs(time.timezone))
print(f'local_time: {local_time}')
import pytz
from datetime import datetime
tz = pytz.timezone('America/Tijuana')
now = datetime.now(tz)
Or you can use arrow https://arrow.readthedocs.io/en/stable/
import arrow
arrow.now('America/New_York')

Python: Convertion of seconds from an initial date to datetime

I have measurements taken from 1st January 1993. They were recorded in second elapsed from that date. I would like to have them in date time.
I know in MatLab the function would be
time = datenum(1993,01,01,00,00, time)
However, I struggle to find an equivalent function in Python.
I have tried:
datetime.fromordinal(time) doesn't work because 'module object has no attribute fromordinal'?
datetime.datetime(time) doesn't work (I have a matrix because there are many scans done)
https://docs.python.org/3/library/datetime.html
You will first have to create a datetime object for Jan 1st 1993 and then add the number of seconds to that date. The code below should help you get started.
from datetime import datetime, timedelta
original_date = datetime.strptime('01-01-1993', '%d-%m-%Y')
original_date + timedelta(seconds= 10000)
output: datetime.datetime(1993, 1, 1, 2, 46, 40)
Let us say you have list of timevalues in seconds starting from 1993-01-01 00:00.
Easiest would be:
datevec=[datetime.datetime(1993,1,1,0)+datetime.timedelta(seconds=val) for val in timevector]
It is like UNIX time, but with a different start.
You can compute the offset once:
>>> import datetime as dt
>>> dt.datetime(1993,1,1).timestamp()
725842800.0
and use it in your program:
OFFSET = 725842800.0
mydate = dt.datetime.fromtimestamp(OFFSET + seconds_from_1993)

Convert local time to UNIX

I'm new to python and I'm trying to get the actual minutes passed every day since 7:00.
I am using mktime to get now_date1 and now_date2 in seconds, and then the plan it's to subtract and divide by 60 to get the minutes.
But I get the following error:
AttributeError: 'str' object has no attribute 'timetuple'
It's this the correct approach?
Here it's the code
import time
import pytz
from datetime import datetime
from time import mktime as mktime
now_date = datetime.now(pytz.timezone('Europe/Bucharest'))
now_date1 = now_date.strftime('%H:%M:%S')
now_date2 = now_date.strftime('7:00:00')
# Convert to Unix timestamp
d1_ts = time.mktime(now_date1.timetuple())
strftime returns a string. Not what you want.
You were pretty close, but there's no need to put time in the mix. Just modify your code like this and use time delta from datetime (inspired by How to calculate the time interval between two time strings):
import pytz
from datetime import datetime
now_date = datetime.now(pytz.timezone('Europe/Bucharest'))
from datetime import datetime
FMT = '%H:%M:%S'
now_date1 = now_date.strftime(FMT)
now_date2 = now_date.strftime('7:00:00')
tdelta = datetime.strptime(now_date1, FMT) - datetime.strptime(now_date2, FMT)
print(tdelta)
I get: 6:40:42 which seems to match since it's 12:42 here.
To get the result in minutes just do:
tdelta.seconds//60
(note that the dates have only correct hour/time/seconds, the year, month, etc.. are 1900 ... since they're not used)
I think something like this might work:
import time
import datetime
from time import mktime as mktime
#current time
now_date = datetime.datetime.now()
#time at 7am
today = datetime.date.today()
now_date2 = datetime.datetime(today.year, today.month, today.day, 7, 0, 0, 0)
#difference in minutes
(now_date - now_date2).days * 24 * 60

Decipher date serial number in Yahoo Finance

I need help deciphering the date number at the end of this url: view-source:http://finance.yahoo.com/q/op?s=XOM&date=1434672000 -- it doesn't look like a proleptic Gregorian serial number, but in Yahoo it designates June 19, 2015. My goal is to write a Python code segment that will create a valid Yahoo date number from my input of yyyymmdd, so that I can generate a valid url for any stock ticker symbol (not just XOM) and option expiration date expressed as yyyymmdd. Thanks!
That's a UNIX timestamp -- the number of seconds since January 1, 1970.
>>> time.gmtime(1434672000)
time.struct_time(tm_year=2015, tm_mon=6, tm_mday=19, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=170, tm_isdst=0)
You can use datetime.fromtimestamp to convert the timestamp into a datetime object:
from datetime import datetime
url="http://finance.yahoo.com/q/op?s=XOM&date=1434672000"
print(datetime.fromtimestamp(float(url.rsplit("=",1)[1])))
2015-06-19 01:00:00
print(datetime.fromtimestamp(float(url.rsplit("=",1)[1])).date())
2015-06-19
To create a timestamp using a date string use strptime to create a datetime object and then call .timestamp():
dte = "2015-06-19"
print(datetime.strptime(dte,"%Y-%m-%d").timestamp())
Using urllib.parse is probably a nicer way to extract the date:
from datetime import datetime
url="http://finance.yahoo.com/q/op?s=XOM&date=1434672000"
from urllib.parse import parse_qs
print(datetime.fromtimestamp(float(parse_qs(url)["date"][0])))
Thank you; now I know how to go both ways with the timestamp (deciphering it, and creating it). Regarding creating it, I found out about the calendar module when I discovered the following code for creating a timestamp from a ddmmmyyyy string (I tested this code in the shell):
#----------------- Create time stamp
import time
import datetime
import calendar
# oxdt stands for 'option expiration date'
oxdt_txt = '15may2015'
oxdt = datetime.datetime.strptime(oxdt_txt, '%d%b%Y')
print(oxdt_txt)
print(oxdt)
print(calendar.timegm(oxdt.utctimetuple()))
print()
oxdt_txt = '19jun2015'
oxdt = datetime.datetime.strptime(oxdt_txt, '%d%b%Y')
print(oxdt_txt)
print(oxdt)
print(calendar.timegm(oxdt.utctimetuple()))
#----------------- done

How can I convert data into "ddmmyyyy hh:mm:ss"?

All that I have is the number 223 (which is the number of days from Jan 01,2012), and the time at which the event occurred at (for example: 09, 55, 56.38 = (hh, mm, ss)).
In Excel I can get a serial number - in the format 10-Aug-12 09:55:56 - with these four numbers.
In Python I've been having some troubles doing the same. Does anyone have any idea about what commands I could be using?
The timedelta class in Python's datetime module lets you create a time difference, in days (or other units), which you can add to/subtract from datetime objects to get a new date.
(Note: the datetime module contains a datetime object. Yup.)
So, you could construct a datetime object using 1st Jan 2012 and the hour, minute and second values you've got, and then add a timedelta of 223 days to it.
To get that datetime as a string in your desired format, the strftime method on the datetime object is your friend.
Putting it all on one line:
from datetime import datetime, timedelta
serial_number = (datetime(2012, 1, 1, 9, 55, 56) + timedelta(223)).strftime('%d-%h-%y %H:%M:%S')

Categories

Resources