Decrypt Date Serial Number in Yahoo Finance
I need help decoding 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 gorgeous Gregorian serial number, but in Yahoo it stands for June 19, 2015. My goal is to write a Python code segment that will generate a valid Yahoo date number from my input yyyymmdd so that I can generate a valid URL for anyone (not just XOM) and an expiration date expressed as yyyymmdd. Thank!
source to share
You can use datetime.fromtimestamp to convert the timestamp to 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())
Usage urllib.parse
is probably the best 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])))
source to share
Thank; now I know how to go both ways with a timestamp (decrypt it and create it). Regarding creating it, I learned about the calendar module when I discovered the following code to create a timestamp from the ddmmmyyyy string (I tested this code in a 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
source to share