Reputation: 1634
I have a database containing dates formatted like: "2015-10-20 22:24:46". I need to convert these dates to UNIX timestamps (UTC), what's the easiest way to do it with Python?
Upvotes: 11
Views: 60630
Reputation: 2696
Without using any 3rd party libraries:
The most straightforward way would be to create a datetime
object from the given date
object and then get a timestamp from it.
from datetime import datetime
dt = datetime(
year=d.year,
month=d.month,
day=d.day,
)
timestamp = int(dt.timestamp())
Upvotes: 19
Reputation: 3551
datetime.datetime.timestamp() has been added in python 3.3. It returns a float (decimals are for the milliseconds), so you must convert it to an integer yourself.
Example use:
from datetime import datetime
def ymdhms_to_timestamp(value: str) -> int:
dt = datetime.strptime(value, "%Y-%m-%d %H:%M:%S")
return int(dt.timestamp())
t = ymdhms_to_timestamp("2015-10-20 22:24:46")
# 1445372686
datetime.fromtimestamp(t)
# datetime.datetime(2015, 10, 20, 22, 24, 46)
Also note that since the formatted date string contains no timezone information, the resulting timestamp will not be UTC if the timezone of the system where the code executes is not. (More generally, if the stored dates were not in the same timezone as your system, the result will be incorrect.)
But if the stored formatted dates were initially UTC, you can rectify the "naive datetime" into a "timezone aware datetime" before converting it to a timestamp.
Example:
from datetime import datetime, timezone
def ymdhms_to_timestamp_utc(value: str) -> int:
naive_dt = datetime.strptime(value, "%Y-%m-%d %H:%M:%S")
utc_dt = naive_dt.replace(tzinfo=timezone.utc)
return int(utc_dt.timestamp())
t = ymdhms_to_timestamp_utc("2015-10-20 22:24:46")
# 1445379886
datetime.fromtimestamp(t)
# datetime.datetime(2015, 10, 21, 0, 24, 46)
Upvotes: 9
Reputation: 4581
from datetime import datetime
import time
dt = datetime.strptime('2015-10-20 22:24:46', '%Y-%m-%d %H:%M:%S')
ts = time.mktime(dt.timetuple())
Upvotes: 7
Reputation: 2061
import time
timestamp = time.mktime(time.strptime('2015-10-20 22:24:46', '%Y-%m-%d %H:%M:%S'))
For more on the format string with all the % symbols, see python's time library.
Upvotes: 24