2

I have a date in excel which is given in: dd mmm yy format i.e.,

29 Jun 18

How do I convert this string into a date object?

I get the error:

time data '13 Jul 18' does not match format '%d %m %Y' 

when I try

datetime.strptime(input, '%d %m %Y')

What should the correct date format be?

1
  • 1
    what did you try so far? Commented Jul 19, 2017 at 7:11

6 Answers 6

2

Since the year in your excell is only two digits (i.e., 18 and not 2018) you need to use %y instead of %Y in your format string:

datetime.strptime(input, '%d %b %y')

For example:

datetime.strptime( '13 Jul 18', '%d %b %y')

Results with:

datetime.datetime(2018, 7, 13, 0, 0)

See this page for more information about date/time string format.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use python datetime module or you can use dateutil parser to parse the string date to valid datetime object. I'd go with dateutil parser as I don't have to define string format. Here is an example

from dateutil.parser import parse
dt = parse("Thu Sep 25 10:36:28 BRST 2003")

Remember to install dateutil by pip install python-dateutil

Comments

0
  • You would have to import datetime and import xlrd

  • Use xlrd to open the excel workbook as

    book = xlrd.open_workbook("Excel.xlsx") sheet = book.sheet_by_name("Worksheet")

  • Use this to convert

    obj = datetime.datetime(*xlrd.xldate_as_tuple(sheet.cell(row,column).value, book.datemode))

Comments

0
from datetime import datetime
datetime.strptime("29 Jun 18", "%d %b %y").date()

Here you get a datetime.date object, I don't know if that's good enough for you. I recommend you to visit the documentation on the module

Comments

0

You can make use of strptime which follows the pattern:

datetime.strptime(date_string, format)

example:

from datetime import datetime
dt = datetime.strptime('19 Jul 2017', '%d %b %y')

Hope this helps :)

Comments

0

Your format is incorrect: %b is Locale's short month and %y is two digit year

import time
time.strptime('13 Jul 18', '%d %b %y')

time.struct_time(tm_year=2018, tm_mon=7, tm_mday=13, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=194, tm_isdst=-1)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.