i have this piece of code:
symbol = 'PSTV'
end_point="https://api.polygon.io/v2/snapshot/locale/us/markets/stocks/tickers/"+symbol+"?apiKey=my_key"
a_json=requests.get(end_point).json()
if a_json['status'] == 'OK':
candle_open = a_json['ticker']['min']['o']
candle_close = a_json['ticker']['min']['c']
candle_high = a_json['ticker']['min']['h']
candle_low = a_json['ticker']['min']['l']
candle_ts = a_json['ticker']['lastQuote']['t']
print(candle_ts/1000000)
candle_ts = datetime.fromtimestamp(candle_ts/1000000).strftime('%Y-%m-%d %H:%M:%S')
print("OK")
im trying to convert timestamp to a readable format like so:
candle_ts = a_json['ticker']['lastQuote']['t'] #get the timestamp
print(candle_ts/1000000)
candle_ts = datetime.fromtimestamp(candle_ts/1000000).strftime('%Y-%m-%d %H:%M:%S')
the print is : 1644529277457.4104
I have no clue why but the error is :
candle_ts = datetime.fromtimestamp(candle_ts/1000000).strftime('%Y-%m-%d %H:%M:%S')
OSError: [Errno 22] Invalid argument
Why do I get such an unusual error??
The value for candle_ts is out of range, as you can see below sample script. The max limit is year 5138 which is around 11digits only. Your value for candle_ts is 13digits.
from datetime import datetime
candle_ts = 1644529277457.4104
try:
candle_ts = datetime.fromtimestamp(candle_ts).strftime('%Y-%m-%d %H:%M:%S')
print(candle_ts)
except Exception as e:
print(e)
Result:
year 54083 is out of range
Related
I'm currently coding an account signup on python and I need the user to enter their date of birth in the format DD/MM/YYYY.
How would I be able to check in the code if the input is valid or not?
dob=input("Enter your date of birth in the format DD/MM/YYYY")
import datetime
try:
date_of_birth = datetime.datetime.strptime(dob, "%d/%m/%Y")
except:
print("Incorrect date!")
Use following code
from datetime import datetime
i = str(raw_input('date'))
try:
dt_start = datetime.strptime(i, '%d/%m/%Y')
except ValueError:
print "Incorrect format"
Try using the datetime library
from datetime import datetime
def validate(date_text):
try:
datetime.datetime.strptime(date_text, '%d/%m/%Y')
except ValueError:
raise ValueError("Incorrect data format, should be YYYY-MM-DD")
Using the following code, I am trying to extract two dates from an object in mongodb and then calculate the difference in time between the two dates -- if both year are in/past 2016. My current code raises the following error:
DeprecationWarning: generator 'QuerySet._iter_results' raised StopIteration
from ipykernel import kernelapp as app
My code:
raw_data = Document.objects()
data = []
for i in raw_data[:10]:
scored = i.date_scored
scored_date = pd.to_datetime(scored, format='%Y-%m-%d %H:%M')
if scored_date == "NoneType":
print("none")
elif scored_date.year >= 2016:
extracted = i.date_extracted
extracted_date = pd.to_datetime(extracted, format='%Y-%m-%d
%H:%M')
bank = i.bank.name
diff = scored_date - extracted_date
print(diff)
datum = [str(bank), str(extracted), str(scored), str(diff)]
data.append(datum)
else:
pass
Any help would be appreciated, thank you!
This is my code:
shift_from = datetime.strptime(shift_change_ob.shift_date, '%Y-%m-%d %H:%M:%S')
shift_to = datetime.strptime(shift_change_ob.shift_date_to, '%Y-%m-%d %H:%M:%S')
shift_time_from = self.get_zone_time(shift_from)
shift_time_to= self.get_zone_time(shift_to)
time_from = datetime.strptime(str(shift_time_from),"%Y-%m-%d %H:%M:%S").strftime("%H.%M")
time_to = datetime.strptime(str(shift_time_to),"%Y-%m-%d %H:%M:%S").strftime("%H.%M")
I want to get only time from shift_time_from and shift_time_to. When I do this I get:
ValueError: unconverted data remains: +00:00
How can I solve this?
If shift_from and shift_to are correct, then use the method time for getting only time part:
shift_time_from = shift_from.time()
shift_time_to = shift_to.time()
I'm receiving this error:
Could not parse 'event_date' as a timestamp. Required format is YYYY-MM-DD HH:MM[:SS[.SSSSSS]]
from BigQuery when I'm trying to insert a row.
This is my code:
bigquery_client = bigquery.Client.from_service_account_json(CREDENTIALS_BIGQUERY, 'roas-164016')
dataset = bigquery_client.dataset(BQ_LOGS_DATASET_NAME)
table = dataset.table(BQ_EMAIL_SENDS_TABLE_NAME)
data = {}
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
data['send_id'] = 'test'
data['uid'] = 'test'
data['account_id'] = 'test'
data['subaccount_id'] = 'test'
data['event_id'] = 'test'
data['event_date'] = now
data['html_content'] = 'test'
data['campaign_name'] = 'test'
data['subject'] = 'test'
data['send_type'] = 'test'
json_data = json.dumps(data)
data = json.loads(json_data)
table.reload()
rows = [data]
errors = table.insert_data(rows)
How can I fix the date formatting?
If that's literally what you need.
now = datetime.now().strftime("%Y-%m-%d %H:%M[:%S[.%f]]")
More likely, the square brackets indicate optional parts. So:
now = datetime.now().strftime("%Y-%m-%d %H:%M")
or
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
or
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
format your date into this YYYY-MM-DD HH:MM:SS
meaning the month day hour minutes and second should be in two digits format.
sample:
2018-02-16 04:39:05 Correct
2018-2-16 4:39:5 wrong
Happy coding!
I got this function below which helps me to change a date format from one to another:
def change_time_format(self, date_string, input_format, output_format):
if date_string == None:
return None
try:
date = datetime.datetime.strptime(date_string, input_format)
timestamp = calendar.timegm(date.timetuple())
new_formatted_date = datetime.datetime.fromtimestamp(timestamp).strftime(output_format)
return new_formatted_date
except Exception as E:
print E
return None
And when i'm calling it like this:
dtu.change_time_format('2017-01-01 12:34:56', '%Y-%m-%d %H:%M:%S', '%d%m%Y %H%M%S')
I'm getting the input as:'01012017 153456' which is wrong and needs to be: '01012017 123456', there is a difference of 3 hours for some reason.
I can't find how to fix it, I searched for several ways over the web and I couldn't find nothing.
From here:
return datetime.datetime.strptime(date_string, input_format).strftime(output_format)