If d = date(2011, 1, 1) is in UTC:

>>> from datetime import datetime, date
>>> import calendar
>>> timestamp1 = calendar.timegm(d.timetuple())
>>> datetime.utcfromtimestamp(timestamp1)
datetime.datetime(2011, 1, 1, 0, 0)

If d is in local timezone:

>>> import time
>>> timestamp2 = time.mktime(d.timetuple()) # DO NOT USE IT WITH UTC DATE
>>> datetime.fromtimestamp(timestamp2)
datetime.datetime(2011, 1, 1, 0, 0)

timestamp1 and timestamp2 may differ if midnight in the local timezone is not the same time instance as midnight in UTC.

mktime() may return a wrong result if d corresponds to an ambiguous local time (e.g., during DST transition) or if d is a past(future) date when the utc offset might have been different and the C mktime() has no access to the tz database on the given platform. You could use pytz module (e.g., via tzlocal.get_localzone()) to get access to the tz database on all platforms. Also, utcfromtimestamp() may fail and mktime() may return non-POSIX timestamp if "right" timezone is used.


To convert datetime.date object that represents date in UTC without calendar.timegm():

DAY = 24*60*60 # POSIX day in seconds (exact value)
timestamp = (utc_date.toordinal() - date(1970, 1, 1).toordinal()) * DAY
timestamp = (utc_date - date(1970, 1, 1)).days * DAY

How can I get a date converted to seconds since epoch according to UTC?

To convert datetime.datetime (not datetime.date) object that already represents time in UTC to the corresponding POSIX timestamp (a float).

Python 3.3+

datetime.timestamp():

from datetime import timezone

timestamp = dt.replace(tzinfo=timezone.utc).timestamp()

Note: It is necessary to supply timezone.utc explicitly otherwise .timestamp() assume that your naive datetime object is in local timezone.

Python 3 (< 3.3)

From the docs for datetime.utcfromtimestamp():

There is no method to obtain the timestamp from a datetime instance, but POSIX timestamp corresponding to a datetime instance dt can be easily calculated as follows. For a naive dt:

timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)

And for an aware dt:

timestamp = (dt - datetime(1970,1,1, tzinfo=timezone.utc)) / timedelta(seconds=1)

Interesting read: Epoch time vs. time of day on the difference between What time is it? and How many seconds have elapsed?

See also: datetime needs an "epoch" method

Python 2

To adapt the above code for Python 2:

timestamp = (dt - datetime(1970, 1, 1)).total_seconds()

where timedelta.total_seconds() is equivalent to (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6 computed with true division enabled.

Example

from __future__ import division
from datetime import datetime, timedelta

def totimestamp(dt, epoch=datetime(1970,1,1)):
    td = dt - epoch
    # return td.total_seconds()
    return (td.microseconds + (td.seconds + td.days * 86400) * 10**6) / 10**6 

now = datetime.utcnow()
print now
print totimestamp(now)

Beware of floating-point issues.

Output

2012-01-08 15:34:10.022403
1326036850.02

How to convert an aware datetime object to POSIX timestamp

assert dt.tzinfo is not None and dt.utcoffset() is not None
timestamp = dt.timestamp() # Python 3.3+

On Python 3:

from datetime import datetime, timedelta, timezone

epoch = datetime(1970, 1, 1, tzinfo=timezone.utc)
timestamp = (dt - epoch) / timedelta(seconds=1)
integer_timestamp = (dt - epoch) // timedelta(seconds=1)

On Python 2:

# utc time = local time              - utc offset
utc_naive  = dt.replace(tzinfo=None) - dt.utcoffset()
timestamp = (utc_naive - datetime(1970, 1, 1)).total_seconds()
Answer from jfs on Stack Overflow
🌐
Python documentation
docs.python.org › 3 › library › datetime.html
datetime — Basic date and time types
Because naive datetime objects are treated by many datetime methods as local times, it is preferred to use aware datetimes to represent times in UTC. As such, the recommended way to create an object representing a specific timestamp in UTC is by calling datetime.fromtimestamp(timestamp, tz=timezone.utc).
Top answer
1 of 12
555

If d = date(2011, 1, 1) is in UTC:

>>> from datetime import datetime, date
>>> import calendar
>>> timestamp1 = calendar.timegm(d.timetuple())
>>> datetime.utcfromtimestamp(timestamp1)
datetime.datetime(2011, 1, 1, 0, 0)

If d is in local timezone:

>>> import time
>>> timestamp2 = time.mktime(d.timetuple()) # DO NOT USE IT WITH UTC DATE
>>> datetime.fromtimestamp(timestamp2)
datetime.datetime(2011, 1, 1, 0, 0)

timestamp1 and timestamp2 may differ if midnight in the local timezone is not the same time instance as midnight in UTC.

mktime() may return a wrong result if d corresponds to an ambiguous local time (e.g., during DST transition) or if d is a past(future) date when the utc offset might have been different and the C mktime() has no access to the tz database on the given platform. You could use pytz module (e.g., via tzlocal.get_localzone()) to get access to the tz database on all platforms. Also, utcfromtimestamp() may fail and mktime() may return non-POSIX timestamp if "right" timezone is used.


To convert datetime.date object that represents date in UTC without calendar.timegm():

DAY = 24*60*60 # POSIX day in seconds (exact value)
timestamp = (utc_date.toordinal() - date(1970, 1, 1).toordinal()) * DAY
timestamp = (utc_date - date(1970, 1, 1)).days * DAY

How can I get a date converted to seconds since epoch according to UTC?

To convert datetime.datetime (not datetime.date) object that already represents time in UTC to the corresponding POSIX timestamp (a float).

Python 3.3+

datetime.timestamp():

from datetime import timezone

timestamp = dt.replace(tzinfo=timezone.utc).timestamp()

Note: It is necessary to supply timezone.utc explicitly otherwise .timestamp() assume that your naive datetime object is in local timezone.

Python 3 (< 3.3)

From the docs for datetime.utcfromtimestamp():

There is no method to obtain the timestamp from a datetime instance, but POSIX timestamp corresponding to a datetime instance dt can be easily calculated as follows. For a naive dt:

timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)

And for an aware dt:

timestamp = (dt - datetime(1970,1,1, tzinfo=timezone.utc)) / timedelta(seconds=1)

Interesting read: Epoch time vs. time of day on the difference between What time is it? and How many seconds have elapsed?

See also: datetime needs an "epoch" method

Python 2

To adapt the above code for Python 2:

timestamp = (dt - datetime(1970, 1, 1)).total_seconds()

where timedelta.total_seconds() is equivalent to (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6 computed with true division enabled.

Example

from __future__ import division
from datetime import datetime, timedelta

def totimestamp(dt, epoch=datetime(1970,1,1)):
    td = dt - epoch
    # return td.total_seconds()
    return (td.microseconds + (td.seconds + td.days * 86400) * 10**6) / 10**6 

now = datetime.utcnow()
print now
print totimestamp(now)

Beware of floating-point issues.

Output

2012-01-08 15:34:10.022403
1326036850.02

How to convert an aware datetime object to POSIX timestamp

assert dt.tzinfo is not None and dt.utcoffset() is not None
timestamp = dt.timestamp() # Python 3.3+

On Python 3:

from datetime import datetime, timedelta, timezone

epoch = datetime(1970, 1, 1, tzinfo=timezone.utc)
timestamp = (dt - epoch) / timedelta(seconds=1)
integer_timestamp = (dt - epoch) // timedelta(seconds=1)

On Python 2:

# utc time = local time              - utc offset
utc_naive  = dt.replace(tzinfo=None) - dt.utcoffset()
timestamp = (utc_naive - datetime(1970, 1, 1)).total_seconds()
2 of 12
117

For unix systems only:

>>> import datetime
>>> d = datetime.date(2011, 1, 1)
>>> d.strftime("%s")  # <-- THIS IS THE CODE YOU WANT
'1293832800'

Note 1: dizzyf observed that this applies localized timezones. Don't use in production.

Note 2: Jakub Narębski noted that this ignores timezone information even for offset-aware datetime (tested for Python 2.7).

Discussions

python - Pandas: Convert Timestamp to datetime.date - Stack Overflow
Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... I’m Jody, the Chief Product and Technology Officer at Stack Overflow. Let’s... 484 Converting between datetime, Timestamp and datetime64 · 61 python datetime fromtimestamp yielding ... More on stackoverflow.com
🌐 stackoverflow.com
Converting python datetime to timestamp and back in UTC still uses local timezone - Stack Overflow
I'm working with a code that gives me utc timestamps and I want to convert them to appropriate datetimes. Unfortunately when I test simple cases with pytz the datetime has an added 6 hours (the CST More on stackoverflow.com
🌐 stackoverflow.com
Converting UTC datetime to timestamp, and then back to UTC datetime
timestamp = datetime.datetime.now().timestamp() edit: sorry that was local time timestamp = datetime.datetime.utcnow().timestamp() More on reddit.com
🌐 r/learnpython
4
1
October 12, 2016
pd.Timestamp vs datetime?
The obvious difference is that pd.Timestamp is part of the pandas module -- so any project that doesn't use pandas will prefer the builtin datetime. Other than that, per pandas documentation: "Timestamp is the pandas equivalent of python’s Datetime and is interchangeable with it in most cases." ( source ) So if you're using pandas it makes sense to use their Timestamp instead of datetime. More on reddit.com
🌐 r/learnpython
1
4
November 29, 2023
🌐
Programiz
programiz.com › python-programming › datetime › timestamp-datetime
Python timestamp to datetime and vice-versa (With Examples)
December 25, 2018 - In Python, we can get timestamp from a datetime object using the datetime.timestamp() method. For example, from datetime import datetime # current date and time now = datetime.now() # convert from datetime to timestamp ts = datetime.timestamp(now) print("Timestamp =", ts)
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-datetime-to-integer-timestamp
Datetime to integer timestamp in Python - GeeksforGeeks
July 23, 2025 - We can convert a datetime object to a timestamp using the built-in timestamp() method, and then round or typecast it to get an integer version. In this article, we'll learn how to convert a Python datetime object into an integer timestamp-either ...
🌐
GitHub
github.com › Nick-heo-eg › ai-execution-boundary-core
GitHub - Nick-heo-eg/ai-execution-boundary-core: Core execution boundary engine (decision + proof + ledger)
3 weeks ago - from agent_execution_guard import ExecutionGuard, Intent, GuardDeniedError, ALLOW_ALL from datetime import datetime, timezone # halt_threshold=39: wire_transfer scores 40 → DENY guard = ExecutionGuard(halt_threshold=39) intent = Intent( actor="agent.finance", action="wire_transfer", payload="wire_transfer amount=50000 to=external", timestamp=datetime.now(timezone.utc), ) try: guard.evaluate(intent, policy=ALLOW_ALL) except GuardDeniedError as e: print(f"Denied: {e.reason}") print(f"Proof: {e.boundary_id}")
Author   Nick-heo-eg
Find elsewhere
🌐
InfluxData
influxdata.com › home › how to convert timestamp to datetime in python | influxdata
How to Convert Timestamp to DateTime in Python | InfluxData
June 28, 2023 - Converting a timestamp to a datetime object is a common task when dealing with time-related data. Python’s datetime module comes to the rescue with the fromtimestamp() function, which allows us to easily perform this conversion.
🌐
Epoch Converter
epochconverter.com › epoch converter › what's the current week number?
What's the Current Week Number? - Epoch Converter
January 5, 2026 - Thanks to everyone who sent me corrections and updates! ... Epoch converter Batch converter Time zone converter Timestamp list LDAP converter .NET DateTime ticks GPS time converter Julian Day converter Chrome/WebKit timestamp Unix hex timestamp Cocoa Core Data timestamp Mac HFS+ timestamp NTP timestamp FAT timestamp SAS timestamp Excel OADate timestamp Seconds/days since year 0 Bin/Oct/Hex converter Year 2038 problem Countdown in seconds Epoch clock
🌐
GeeksforGeeks
geeksforgeeks.org › pandas › pandas-timestamp-to-datetime
Pandas Timestamp To Datetime - GeeksforGeeks
July 23, 2025 - First, we create a timestamp object using Components (year, month, day, hour, minute, second, microsecond) and convert it to a DateTime object using the Pandas.to_pydatetime() function. Python ·
🌐
MySQL
dev.mysql.com › doc › refman › 8.4 › en › integer-types.html
MySQL :: MySQL 8.4 Reference Manual :: 13.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT
MySQL supports the SQL standard integer types INTEGER (or INT) and SMALLINT. As an extension to the standard, MySQL also supports the integer types TINYINT, MEDIUMINT, and BIGINT. The following table shows the required storage and range for each integer type · Table 13.1 Required Storage and ...
🌐
Devnote
devnote.in › home › blog › how to convert timestamp to date and time in python
How To Convert Timestamp To Date and Time in Python - Devnote
October 26, 2020 - This tutorial is How To Convert Timestamp To Date and Time in Python. python timestamp to date and time convert using ctime(),gmtime(),strftime(), and fromtimestamp() function. You can use the fromtimestamp function from the datetime module ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-convert-timestamp-string-to-datetime-object-in-python
How to convert timestamp string to datetime object in Python? - GeeksforGeeks
August 23, 2025 - Explanation: s is parsed automatically ... ISO 8601 format (i.e., "YYYY-MM-DD HH:MM:SS"), fromisoformat() is the cleanest and most efficient method to convert it to a datetime object....
🌐
Reddit
reddit.com › r/learnpython › converting utc datetime to timestamp, and then back to utc datetime
r/learnpython on Reddit: Converting UTC datetime to timestamp, and then back to UTC datetime
October 12, 2016 -

I'm having trouble taking a UTC datetime, converting it to a timestamp, and then converting that timestamp back into a datetime object. I have read this post and this post, but following the answers isn't working for me either.

I'm using Python 3.4

I'm trying to use timezone-aware datetimes, but I suspect I am not doing it correctly. Here is an example of what I'm trying:

import datetime
import pytz

now = datetime.datetime.utcnow()
timestamp = now.timestamp()

now2 = datetime.datetime.utcfromtimestamp(timestamp)

This does not work. I've also tried to replace the last line with:

now2 = datetime.datetime.utcfromtimestamp(timestamp).replace(pytz.utc)

But that gave me a datetime with the same hours, just with an extra timezone object inside the datetime object.

I need now2 to equal now. I don't care about my local timezone. I need this all to be in UTC.

What am I missing?

🌐
W3Schools
w3schools.com › python › python_datetime.asp
Python Datetime
A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.to_datetime.html
pandas.to_datetime — pandas 3.0.1 documentation
If Timestamp convertible (Timestamp, dt.datetime, np.datetimt64 or date string), origin is set to Timestamp identified by origin.
Top answer
1 of 4
522

datetime.datetime.fromtimestamp() is correct, except you are probably having timestamp in miliseconds (like in JavaScript), but fromtimestamp() expects Unix timestamp, in seconds.

Do it like that:

>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)

and the result is:

>>> date
datetime.datetime(2012, 3, 16, 1, 0)

Does it answer your question?

EDIT: jfs correctly suggested in a now-deleted comment to use true division by 1e3 (float 1000). The difference is significant, if you would like to get precise results, thus I changed my answer. The difference results from the default behaviour of Python 2.x, which always returns int when dividing (using / operator) int by int (this is called floor division). By replacing the divisor 1000 (being an int) with the 1e3 divisor (being representation of 1000 as float) or with float(1000) (or 1000. etc.), the division becomes true division. Python 2.x returns float when dividing int by float, float by int, float by float etc. And when there is some fractional part in the timestamp passed to fromtimestamp() method, this method's result also contains information about that fractional part (as the number of microseconds).

2 of 4
18

Alternatively, you can use pandas.to_datetime and choose the units for yourself together with the timezone. That avoids all the comments and problems mentioned in the previous answer:

import pandas as pd

pd.to_datetime(int('1331856000000'), utc=True, unit='ms')
# Timestamp('2012-03-16 00:00:00+0000', tz='UTC')
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.Timestamp.to_pydatetime.html
pandas.Timestamp.to_pydatetime — pandas 3.0.1 documentation
>>> ts = pd.Timestamp('2020-03-14T15:32:52.192548') >>> ts.to_pydatetime() datetime.datetime(2020, 3, 14, 15, 32, 52, 192548)
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.Timestamp.html
pandas.Timestamp — pandas 3.0.1 documentation
Python datetime.datetime object. ... There are essentially three calling conventions for the constructor. The primary form accepts four parameters. They can be passed by position or keyword. The other two forms mimic the parameters from datetime.datetime. They can be passed by either position or keyword, but not both mixed together. ... >>> pd.Timestamp(1513393355, unit='s', tz='US/Pacific') Timestamp('2017-12-15 19:02:35-0800', tz='US/Pacific')