Skip to content

Instantly share code, notes, and snippets.

@deehzee
Last active March 9, 2017 10:34
Show Gist options
  • Save deehzee/5a9368ebc079463450693aeb893f286f to your computer and use it in GitHub Desktop.
Save deehzee/5a9368ebc079463450693aeb893f286f to your computer and use it in GitHub Desktop.
How to convert date-time into timestamp and vice versa.

Conversion between timestamp and human date-time

Different ways to convert time between human readable format and timestamps.

import time

# How to convert from human datetime in local time to timestamp (s)
print(int(time.mktime(time.strptime('2017-03-09 15:39:30', '%Y-%m-%d %H:%M:%S'))))

# How to convert timestamps (s) to datetime in localtime...
print(time.strftime('%a, %Y-%m-%d %H:%M:%S %z', time.localtime(1489054170)))

Or,

import calendar
import dateparser
import time

# From human to timestamp (s)
tm = dateparser.parse('2017-03-09 15:39:30')
print(calendar.timegm(tm.timetuple()) + time.timezone)

Or, using pandas...

import pandas as pd
import time

# From timestamp to human in local time
print(pd.to_datetime(1489054170 - time.timezone, unit='s'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment