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!

+3


source to share


3 answers


This is 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)

      

+2


source


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])))

      

+1


source


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

      

0


source







All Articles