10

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?

2
  • 1
    I'm assuming by timestamp you mean seconds since the epoch. If you want a datetime object... oh someone just gave an answer that shows how to do that.
    – Nick White
    Commented Nov 10, 2015 at 2:19
  • 1
    what is the input timezone? Is it local time? What do you want to do with ambiguous time (e.g., during DST transitions)? Are the timestamps ordered? May your input timezone have a different utc offset in the past/future? Does mktime() have access to a historical timezone database on your system (to get the correct utc offset for a date)? In general, a portable solution should use pytz (the tz database), tzlocal (for the local timezone) modules.
    – jfs
    Commented Nov 10, 2015 at 8:37

4 Answers 4

24
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.

19

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())
2
  • Although I don't like this verbosity, it's the only answer that correctly transforms a Python date into a timestamp. Commented Oct 18, 2020 at 17:58
  • How could we captures its * 1000 version
    – alper
    Commented Jul 30, 2021 at 15:57
9

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)
7
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())
1
  • 2
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.
    – Ajean
    Commented Nov 10, 2015 at 2:35

Not the answer you're looking for? Browse other questions tagged or ask your own question.