Skip to content

Instantly share code, notes, and snippets.

@gennad
Created June 10, 2011 07:15
Show Gist options
  • Save gennad/1018376 to your computer and use it in GitHub Desktop.
Save gennad/1018376 to your computer and use it in GitHub Desktop.
Python string to timestamp
import datetime
import time
def from_string_to_timestamp(st):
if st.find('-') != -1:
splitted = st.split('-')
else:
splitted = st.split('.')
try:
day = int(splitted[0])
month = int(splitted[1])
year = int(splitted[2])
except IndexError:
raise FormatError()
dt = datetime.datetime(year, month, day)
if year < 1970:
epoch = datetime.datetime(1970, 1, 1)
diff = dt-epoch
timestamp = diff.days * 24 * 3600 + diff.seconds
else:
timestamp = time.mktime(dt.timetuple())
timestamp = int(timestamp)
MAGIC_NUMBER = 25200 # Adds 8 hours
return timestamp + MAGIC_NUMBER
class FormatError(Exception):
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment