337

How to convert a string in the format "%d/%m/%Y" to timestamp?

"01/12/2011" -> 1322697600
4
  • What's the 2nd number? Unix Epoch time?
    – Hasteur
    Mar 9, 2012 at 16:55
  • 5
    @Hasteur, yes. The second number represents the number of seconds that have passed between the beginning of the unix epoch and the date specified. This format is also referred to as POSIX time.
    – eikonomega
    Nov 5, 2013 at 17:01
  • 1
    Time is passing very fast! you have asked this question at 13... and now is 16...
    – Amir Fo
    Sep 29, 2020 at 9:44

17 Answers 17

443
>>> import time
>>> import datetime
>>> s = "01/12/2011"
>>> time.mktime(datetime.datetime.strptime(s, "%d/%m/%Y").timetuple())
1322697600.0
13
  • 12
    it assumes midnight 01/12/2011 in local timezone. If input is in UTC; you could use calendar.timegm() or .toordinal()
    – jfs
    Nov 17, 2013 at 19:56
  • 87
    datetime.datetime.strptime(s, "%d/%m/%Y").timestamp() is a bit shorter
    – Tim Diels
    Feb 25, 2014 at 0:16
  • 23
    @timdiels: again. .timestamp() assumes local time instead of UTC if no explicit timezone is given. The code in the answer works (produces expected 1322697600) only on a computer where local timezone has zero utc offset.
    – jfs
    Mar 27, 2014 at 8:31
  • 13
    this doesn't work: datetime.datetime.strptime("2014:06:28 11:53:21", "%Y:%m:%d %H:%M:%S").timestamp() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'datetime.datetime' object has no attribute 'timestamp' Jan 30, 2015 at 12:07
  • 5
    @ZdenekMaxa datetime.timestamp() available only for python >= 3.3 versions. docs.python.org/3/whatsnew/3.3.html
    – joni jones
    Feb 5, 2015 at 13:02
81

I use ciso8601, which is 62x faster than datetime's strptime.

t = "01/12/2011"
ts = ciso8601.parse_datetime(t)
# to get time in seconds:
time.mktime(ts.timetuple())

You can learn more here.

5
  • 6
    this is a fantastic suggestion. i just used it and shaved TONS of time off of my execution.
    – David
    Aug 4, 2015 at 17:23
  • 7
    My god this is fast
    – Hews
    Dec 23, 2018 at 21:02
  • 8
    And +1 for not needing me to spell out what the time string format is.
    – gowenfawr
    May 7, 2019 at 12:14
  • @gowenfawr There is also datetime.fromisoformat which can parse datetime.fromisoformat(str(datetime.now())) correctly. However, it doesn't work with JavaScript's new Date().toISOString() which is also ISO 8601. python-dateutil is better at guessing, but it may also guess regional format wrong.
    – Polv
    Feb 23, 2022 at 21:50
  • 1
    For this to work, you need Microsoft Visual C++ 14.0 link Mar 21, 2022 at 5:39
51

Simply use datetime.datetime.strptime:

import datetime
stime = "01/12/2011"
print(datetime.datetime.strptime(stime, "%d/%m/%Y").timestamp())

Result:

1322697600

To use UTC instead of the local timezone use .replace:

datetime.datetime.strptime(stime, "%d/%m/%Y").replace(tzinfo=datetime.timezone.utc).timestamp()
2
  • 3
    For a complete anwser you must say that it is only valid for python 3.3+
    – Eduardo
    Jan 1, 2020 at 16:34
  • On the first example, the result is a float not int Jun 17, 2020 at 15:47
49
>>> int(datetime.datetime.strptime('01/12/2011', '%d/%m/%Y').strftime("%s"))
1322683200
3
46

To convert the string into a date object:

from datetime import date, datetime

date_string = "01/12/2011"
date_object = date(*map(int, reversed(date_string.split("/"))))
assert date_object == datetime.strptime(date_string, "%d/%m/%Y").date()

The way to convert the date object into POSIX timestamp depends on timezone. From Converting datetime.date to UTC timestamp in Python:

  • date object represents midnight in UTC

    import calendar
    
    timestamp1 = calendar.timegm(utc_date.timetuple())
    timestamp2 = (utc_date.toordinal() - date(1970, 1, 1).toordinal()) * 24*60*60
    assert timestamp1 == timestamp2
    
  • date object represents midnight in local time

    import time
    
    timestamp3 = time.mktime(local_date.timetuple())
    assert timestamp3 != timestamp1 or (time.gmtime() == time.localtime())
    

The timestamps are different unless midnight in UTC and in local time is the same time instance.

8
  • When I run the examples in this post, I get the error: NameError: name 'wckCalendar' is not defined. I am running Python 3.4.1 on a Windows 32 bits machine. Any idea? Thanks.
    – sedeh
    Aug 14, 2014 at 1:46
  • 1
    @sedeh there is no wckCalendar in the post. Check your code.
    – jfs
    Aug 14, 2014 at 2:55
  • @J.F.Sebastian Exactly, and I wasn't trying to call wckCalendar directly. It just shows up in the error message. See my post here discussing the problem.
    – sedeh
    Aug 14, 2014 at 3:05
  • 1
    @törzsmókus: If the answer is wrong, It doesn't matter how readable it is.
    – jfs
    Sep 18, 2017 at 11:11
  • 1
    @törzsmókus: look at my answer: it may produce two different numbers. Your answer produces one number without mentioning which one.
    – jfs
    Sep 18, 2017 at 11:26
30

The answer depends also on your input date timezone. If your date is a local date, then you can use mktime() like katrielalex said - only I don't see why he used datetime instead of this shorter version:

>>> time.mktime(time.strptime('01/12/2011', "%d/%m/%Y"))
1322694000.0

But observe that my result is different than his, as I am probably in a different TZ (and the result is timezone-free UNIX timestamp)

Now if the input date is already in UTC, than I believe the right solution is:

>>> calendar.timegm(time.strptime('01/12/2011', '%d/%m/%Y'))
1322697600
2
  • 1
    I think this is better. No need to import both 'time' and 'datetime'.
    – kennyut
    Jul 12, 2017 at 15:10
  • how to handle date in format "YYYY-MM-DD"?
    – n0obcoder
    Apr 17, 2021 at 11:00
9

I would give a answer for beginners (like me):

You have the date string "01/12/2011". Then it can be written by the format "%d/%m/%Y". If you want to format to another format like "July 9, 2015", here a good cheatsheet.

  • Import the datetime library.

  • Use the datetime.datetime class to handle date and time combinations.

  • Use the strptime method to convert a string datetime to a object datetime.

  • Finally, use the timestamp method to get the Unix epoch time as a float. So,

import datetime
print( int( datetime.datetime.strptime( "01/12/2011","%d/%m/%Y" ).timestamp() ) )

# prints 1322712000
8

A lot of these answers don't bother to consider that the date is naive to begin with

To be correct, you need to make the naive date a timezone aware datetime first

import datetime
import pytz
# naive datetime
d = datetime.datetime.strptime('01/12/2011', '%d/%m/%Y')
>>> datetime.datetime(2011, 12, 1, 0, 0)

# add proper timezone
pst = pytz.timezone('America/Los_Angeles')
d = pst.localize(d)
>>> datetime.datetime(2011, 12, 1, 0, 0,
tzinfo=<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>)

# convert to UTC timezone
utc = pytz.UTC
d = d.astimezone(utc)
>>> datetime.datetime(2011, 12, 1, 8, 0, tzinfo=<UTC>)

# epoch is the beginning of time in the UTC timestamp world
epoch = datetime.datetime(1970,1,1,0,0,0,tzinfo=pytz.UTC)
>>> datetime.datetime(1970, 1, 1, 0, 0, tzinfo=<UTC>)

# get the total second difference
ts = (d - epoch).total_seconds()
>>> 1322726400.0

Also:

Be careful, using pytz for tzinfo in a datetime.datetime DOESN'T WORK for many timezones. See datetime with pytz timezone. Different offset depending on how tzinfo is set

# Don't do this:
d = datetime.datetime(2011, 12, 1,0,0,0, tzinfo=pytz.timezone('America/Los_Angeles'))
>>> datetime.datetime(2011, 1, 12, 0, 0, 
tzinfo=<DstTzInfo 'America/Los_Angeles' LMT-1 day, 16:07:00 STD>)
# tzinfo in not PST but LMT here, with a 7min offset !!!

# when converting to UTC:
d = d.astimezone(pytz.UTC)
>>> datetime.datetime(2011, 1, 12, 7, 53, tzinfo=<UTC>)
# you end up with an offset

https://en.wikipedia.org/wiki/Local_mean_time

6

First you must the strptime class to convert the string to a struct_time format.

Then just use mktime from there to get your float.

6

I would suggest dateutil:

import dateutil.parser
dateutil.parser.parse("01/12/2011", dayfirst=True).timestamp()
3
  • It is wrong. OP expects time in "%d/%m/%Y" format. Compare: dateutil.parser.parse("01/02/2001") and datetime.strptime("01/02/2001", "%d/%m/%Y")
    – jfs
    Sep 18, 2017 at 11:47
  • thanks @jfs, good catch. I updated my answer accordingly. (as a non-American, I wouldn’t have thought the illogical M/D/Y format was the default for the parser.) Sep 18, 2017 at 12:20
  • 2
    it doesn't produce the expected 1322697600 unless your local timezone is UTC. See my comment from 2014
    – jfs
    Apr 22, 2018 at 16:32
6

Seems to be quite efficient:

import datetime
day, month, year = '01/12/2011'.split('/')
datetime.datetime(int(year), int(month), int(day)).timestamp()

1.61 µs ± 120 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

2
  • 1
    What's the datetime function? datetime from the datetime library doesn't support .timestamp()
    – Joooeey
    Apr 17, 2018 at 0:18
  • 2
    @Joooeey: It does, on Python 3.3 or later. Wasn't available when the question was posted, but it's been available since Sept. of 2012. Mar 19, 2019 at 5:38
5

you can convert to isoformat

my_date = '2020/08/08'
my_date = my_date.replace('/','-') # just to adapte to your question
date_timestamp = datetime.datetime.fromisoformat(my_date).timestamp()
3

The easiest way

from datetime import datetime
    
    s = "01/12/2011"
    sec = datetime.strptime(s,"%d/%m/%Y").timestamp()

And if you want to use time zone

from django.utils import timezone
from datetime import datetime
        
s = "01/12/2011"
sec=datetime.strptime(s,"%d/%m/%Y").replace(tzinfo=timezone.utc).timestamp())
1
  • Answer needs supporting information Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – moken
    Aug 5, 2023 at 5:03
1

You can refer this following link for using strptime function from datetime.datetime, to convert date from any format along with time zone.

https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior

1

A simple function to get UNIX Epoch time.

NOTE: This function assumes the input date time is in UTC format (Refer to comments here).

def utctimestamp(ts: str, DATETIME_FORMAT: str = "%d/%m/%Y"):
    import datetime, calendar
    ts = datetime.datetime.utcnow() if ts is None else datetime.datetime.strptime(ts, DATETIME_FORMAT)
    return calendar.timegm(ts.utctimetuple())

Usage:

>>> utctimestamp("01/12/2011")
1322697600
>>> utctimestamp("2011-12-01", "%Y-%m-%d")
1322697600
0

just use datetime.timestamp(your datetime instanse), datetime instance contains the timezone infomation, so the timestamp will be a standard utc timestamp. if you transform the datetime to timetuple, it will lose it's timezone, so the result will be error. if you want to provide an interface, you should write like this: int(datetime.timestamp(time_instance)) * 1000

-1

You can go both directions, unix epoch <==> datetime :

import datetime
import time


the_date = datetime.datetime.fromtimestamp( 1639763585 )



unix_time = time.mktime(the_date.timetuple())

assert  ( the_date == datetime.datetime.fromtimestamp(unix_time) ) & \
        ( time.mktime(the_date.timetuple()) == unix_time         )   

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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