0

I'm trying to convert my date string to ISO format but it's not working. Any suggestions on efficiently doing this with datetime, time, or pandas?

date = "2/3/13"
import datetime
t = datetime.date(*map(int,date.split("/")))
format = "'%Y-%m-%d'"
t.strftime(format)
# "'0002-03-13'"
O.rka
  • 29,847
  • 68
  • 194
  • 309
  • Possible duplicate of [Converting string into datetime](https://stackoverflow.com/questions/466345/converting-string-into-datetime) – Anton vBR Nov 28 '17 at 21:53

2 Answers2

4

With pandas -

pd.to_datetime("2/3/13")
Timestamp('2013-02-03 00:00:00')

With pandas, you can (most of the time) infer the format without having to manually specify it. However, it would seem pointless to import such a heavy module to use it only for a simple datetime conversion.

For that reason, here's an equally simple python way using strptime -

from datetime import datetime as dt

dt.strptime("2/3/13", '%d/%m/%y')
datetime.datetime(2013, 3, 2, 0, 0)

Or, even simpler (you don't have to pass a format string), using dateutil -

from dateutil import parser

parser.parse('2/3/13/').date()
datetime.date(2013, 2, 3)

pandas actually uses the dateutil library under the hood (– unutbu). If your date strings are consistent in structure, I'd recommend using one of these.

cs95
  • 379,657
  • 97
  • 704
  • 746
  • Thanks! Is there a way to not include the time stamps? I could just do: `str(x).split(" ")[0]` but I wasn't sure if there was an argument for that – O.rka Nov 28 '17 at 21:49
  • 1
    @BradSolomon Haha I asked a similar question, and the answers to it might help: https://stackoverflow.com/questions/46842793/datetime-conversion-how-to-extract-the-inferred-format – cs95 Nov 28 '17 at 21:49
  • 1
    @BradSolomon: pandas uses [dateutil](https://dateutil.readthedocs.io/en/stable/parser.html) – unutbu Nov 28 '17 at 21:49
  • 1
    @O.rka `dt.strptime("2/3/13", '%d/%m/%y').date()` – cs95 Nov 28 '17 at 21:51
  • @O.rka I don't believe you can omit timestamps if you're using pandas. – cs95 Nov 28 '17 at 21:53
  • These are all great. There's a few resources online that explain the datetime module but special cases are a little difficult to find. This will be really useful for a quick reference of different methods. – O.rka Nov 28 '17 at 22:10
0

I love me some libraries when it comes to working with date/times. dateparser, parsedatetime, and arrow are all really good choices

import dateparser as dp

print(dp.parse("2/13/13"))
2013-02-13 00:00:00

print(dp.parse("2/13/13").date())
2013-02-13

print(dp.parse("Yesterday at 2am PST"))
2017-11-27 13:56:59.290385-08:00

Cheers

SteveJ
  • 3,034
  • 2
  • 27
  • 47