Created
June 10, 2011 07:15
-
-
Save gennad/1018376 to your computer and use it in GitHub Desktop.
Python string to timestamp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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