329

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

"01/12/2011" -> 1322697600
jfs
  • 399,953
  • 195
  • 994
  • 1,670
Shankar Cabus
  • 9,302
  • 7
  • 33
  • 43
  • What's the 2nd number? Unix Epoch time? – Hasteur Mar 09 '12 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 05 '13 at 17:01
  • 1
    Time is passing very fast! you have asked this question at 13... and now is 16... – Amir Fo Sep 29 '20 at 09:44
  • https://stackoverflow.com/questions/11743019/convert-python-datetime-to-epoch-with-strftime – Stefano G. May 04 '21 at 15:01

17 Answers17

436
>>> import time
>>> import datetime
>>> s = "01/12/2011"
>>> time.mktime(datetime.datetime.strptime(s, "%d/%m/%Y").timetuple())
1322697600.0
Katriel
  • 120,462
  • 19
  • 136
  • 170
  • 12
    it assumes midnight 01/12/2011 in local timezone. If input is in UTC; you could use [`calendar.timegm()` or `.toordinal()`](http://stackoverflow.com/a/20035328/4279) – jfs Nov 17 '13 at 19:56
  • +1 There's a lot more to say about this topic and I probably should have said a lot of it. In particular, `dd/mm/YYYY` is a symbolic date, and to convert from a symbolic date to an instant you must specify a timezone. – Katriel Nov 19 '13 at 15:11
  • `1322697600` result from the question hints at UTC timezone. – jfs Jan 07 '14 at 13:55
  • 86
    `datetime.datetime.strptime(s, "%d/%m/%Y").timestamp()` is a bit shorter – Tim Diels Feb 25 '14 at 00: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 '14 at 08: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 "", line 1, in AttributeError: 'datetime.datetime' object has no attribute 'timestamp' – Zdenek Maxa Jan 30 '15 at 12:07
  • 5
    @ZdenekMaxa datetime.timestamp() available only for python >= 3.3 versions. https://docs.python.org/3/whatsnew/3.3.html – joni jones Feb 05 '15 at 13:02
  • 2
    @kenorb: it is incorrect. `mktime()` expects local time but you pass it utc time. It has the same issue as this answer: it produces a wrong result unless the utc offset in the local timezone is zero. – jfs Apr 30 '16 at 12:36
  • @J.F.Sebastian I don't think that is true. A timestamp data type holds no timezone information at all. In fact, try to test both lines of code and you will see that they send the exact same inforamtion. – Konrad Jul 07 '17 at 14:11
  • @Konrad what are talking about? What lines? what my statement is false in your opinion? (quote it verbatim) – jfs Jul 07 '17 at 14:17
  • 1
    You say: "@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. " I'm saying that `time.mktime(datetime.datetime.strptime(s, "%d/%m/%Y").timetuple())` and `datetime.datetime.strptime(s, "%d/%m/%Y").timestamp()` are equivalent – Konrad Jul 07 '17 at 14:19
  • @Konrad 1- do you understand that the local timezone is not necessarily UTC? 2- do you understand that the example in the question assumes UTC? 3- do you understand that both time.mktime and datetime.timestamp() should not be used with a naive datetime instance that represents (in this case) the time in UTC? (As it is said in my previous comments) – jfs Jul 07 '17 at 16:07
  • **[Readability counts.](https://www.python.org/dev/peps/pep-0020/#the-zen-of-python)** See my answer with _dateutil_ for a far more human-readable solution. – törzsmókus Sep 18 '17 at 09:07
80

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.

buran
  • 13,682
  • 10
  • 36
  • 61
Eyal Ch
  • 9,552
  • 5
  • 44
  • 54
  • 6
    this is a fantastic suggestion. i just used it and shaved TONS of time off of my execution. – David Aug 04 '15 at 17:23
  • 7
    My god this is fast – Hews Dec 23 '18 at 21:02
  • 8
    And +1 for not needing me to spell out what the time string format is. – gowenfawr May 07 '19 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 '22 at 21:50
  • 1
    For this to work, you need Microsoft Visual C++ 14.0 [link](https://visualstudio.microsoft.com/visual-cpp-build-tools/) – Mario Ariyanto Mar 21 '22 at 05:39
47
>>> int(datetime.datetime.strptime('01/12/2011', '%d/%m/%Y').strftime("%s"))
1322683200
San4ez
  • 8,091
  • 4
  • 41
  • 62
  • 14
    [`"%s"` is not supported by Python](http://stackoverflow.com/q/17433056/4279). It is not portable. – jfs Nov 17 '13 at 19:59
  • 1
    **[Readability counts.](https://www.python.org/dev/peps/pep-0020/#the-zen-of-python)** See my answer with _dateutil_ for a far more human-readable solution. – törzsmókus Sep 18 '17 at 09:09
  • this is the answer:https://stackoverflow.com/questions/11743019/convert-python-datetime-to-epoch-with-strftime – Stefano G. May 04 '21 at 15:00
46

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()
45

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.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670
  • 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 '14 at 01:46
  • 1
    @sedeh there is no wckCalendar in the post. Check your code. – jfs Aug 14 '14 at 02: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](http://stackoverflow.com/questions/25299371/converting-string-date-to-timestamp-in-python-3-4) discussing the problem. – sedeh Aug 14 '14 at 03:05
  • @sedeh: I [left a comment on your question](http://stackoverflow.com/questions/25299371/converting-string-date-to-timestamp-in-python-3-4#comment39430758_25299371). Also, If input date is in local timezone (as `time.mktime()` in your code suggests) then you could use `.timestamp()` method to get the timestamp in Python 3.4. [Follow the link in the post](http://stackoverflow.com/a/8778548/4279). – jfs Aug 14 '14 at 03:20
  • **[Readability counts.](https://www.python.org/dev/peps/pep-0020/#the-zen-of-python)** See my answer with _dateutil_ for a far more human-readable solution. – törzsmókus Sep 18 '17 at 09:09
  • 1
    @törzsmókus: If the answer is wrong, It doesn't matter how readable it is. – jfs Sep 18 '17 at 11:11
  • @jfs is my answer wrong? I don't think so, but if you do please take the time to leave a comment there. – törzsmókus Sep 18 '17 at 11:14
  • 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 '17 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
Nowakus
  • 571
  • 4
  • 7
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
alfredo
  • 524
  • 6
  • 9
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

MrE
  • 19,584
  • 12
  • 87
  • 105
6

I would suggest dateutil:

import dateutil.parser
dateutil.parser.parse("01/12/2011", dayfirst=True).timestamp()
törzsmókus
  • 1,799
  • 2
  • 21
  • 28
  • 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 '17 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.) – törzsmókus Sep 18 '17 at 12:20
  • 2
    it doesn't produce the expected `1322697600` unless your local timezone is UTC. See [my comment from 2014](https://stackoverflow.com/questions/9637838/convert-string-date-to-timestamp-in-python/20035328#comment34554753_9637908) – jfs Apr 22 '18 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)

Gerard
  • 177
  • 3
  • 7
  • 1
    What's the `datetime` function? `datetime` from the `datetime` library doesn't support `.timestamp()` – Joooeey Apr 17 '18 at 00:18
  • 2
    @Joooeey: [It does, on Python 3.3 or later](https://docs.python.org/3/library/datetime.html#datetime.datetime.timestamp). Wasn't available when the question was posted, but it's been available since Sept. of 2012. – ShadowRanger Mar 19 '19 at 05:38
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.

Cryptite
  • 1,426
  • 2
  • 28
  • 50
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()
Aliens Dev
  • 251
  • 4
  • 5
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

Arjun Sankarlal
  • 2,655
  • 1
  • 9
  • 18
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
gihanchanuka
  • 4,783
  • 2
  • 32
  • 32
1

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())
ali
  • 118
  • 6
  • 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](https://stackoverflow.com/help/how-to-answer). – moken Aug 05 '23 at 05:03
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

user6689187
  • 101
  • 3
-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         )