Convert date string in excel to date object in python - python

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?

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.

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

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

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

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 :)

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)

Related

Python 3.7: converting a string with different timezone into date

I am trying to convert a string into date format in Python.
I am using following statement
datetime_obj = datetime.datetime.strptime("Sun Aug 19 16:24:31 PDT 2018", "%a %b %d %H:%M:%S %Z %Y")
However, I get an error -
ValueError: time data 'Sun Aug 19 16:24:31 PDT 2018' does not match format '%a %b %d %H:%M:%S %Z %Y'
If I remove the timezone from the date string and the format string, the code works perfect. Which leads me to believe that the issue is related to the timezone but I am not sure what actions should be taken.
I am in eastern timezone and the time zone in the string is in Pacific timezone.
Appreciate any help on this.
As mentioned in this answer you can use python-dateutil for this:
>>> from dateutil import parser
>>> datetime_obj = parser.parse("Sun Aug 19 16:24:31 PDT 2018")
datetime.datetime(2018, 8, 19, 16, 24, 31)
Standard datetime module behaves very strangely with parsing timezones, as I see reading this answer in question related to similar problem.

Convert string to DateTime for mysql in python

I want to convert my date into DateTime object for MySQL.
My string format is: Mon Aug 27 04:47:45 +0000 2018
Expected Output: 'YYYY-M-D H:mm:ss'
from datetime import datetime
t = datetime.strptime('Mon Aug 27 04:47:45 +0000 2008', '%a %b %d %H:%M:%S % z %Y')
t.strftime('%Y-%m-%d %H:%M:%S')
Refer section 8.1.8
here
If you are using python 3, this solution would work -
from datetime import datetime
x = 'Mon Aug 27 04:47:45 +0000 2018'
x = datetime.strftime(datetime.strptime(x, '%a %b %d %I:%M:%S %z %Y'), '%Y-%m-%d %H:%M:%S')
# OP '2018-08-27 04:47:45'
But for python 2, you might get a ValueError: 'z' is a bad directive.... In that case, you'll either have to use something like pytz or dateutil. The table that you need to look for all these conversions can be found here
Edit: You can't have Expected Output: 'YYYY-M-D H:mm:ss' if you convert your datetime string to datetime object. Datetime object has it's own format. Above gives you a string of the format that you want
from datetime import datetime
date_as_dt_object = datetime.strptime(dt, '%a %b %d %H:%M:%S %z %Y')
You can use date_as_dt_object in a raw query or an ORM. If used in a raw query pass it as a string like:
query = "select * from table where date >" + str(date_as_dt_object)
Check out this list for Python's strftime directives.
http://strftime.org/

Format Unicode time value

I have next time value in unicode (<type 'unicode'>):
2017-08-09T15:02:58+0000.
How to convert it to friendly view (e.g. Day, Month of Year)?
This should do what you ask:
from datetime import datetime
a = '2017-08-09T15:02:58+0000'
datetime.strptime(a[:-5], '%Y-%m-%dT%H:%M:%S').strftime('%d, %b of %Y')
#09, Aug of 2017
strptime method throws error for timezone parameter that doesn't seem to interest you so I removed that part with a[:-5].
For the rest of the string you can just follow guidelines from datetime docs.
Using the same docs you can construct your datetime string using strftime() method like you wanted '%d, %b of %Y' or in plain words [day], [abbreviated month] of [Year]
try this
import datetime
today = datetime.date.today()
print today.strftime('We are the %d, %b %Y')
'We are the 22, Nov 2008'

How convert this string to iso 8601 with Python

I have this string
14 Mai 2014
I want to convert it to iso 8601
i read this answer and this one,
and first i try to convert string to date and then in i convert it to iso format:
test_date = datetime.strptime("14 Mai 2014", '%d %m %Y')
iso_date = test_date.isoformat()
i got this error:
ValueError: time data '14 Mai 2014' does not match format '%d %m %Y'
According to Python strftime reference %m means day of month and in your case "Mai" seems to be name of month in your current locale and you have to use this %b format. So your piece of code should looks like this:
test_date = datetime.strptime("14 Mai 2014", '%d %b %Y')
iso_date = test_date.isoformat()
And don't forget to set locale.
For English locale it works:
>>> from datetime import datetime
>>> test_date = datetime.strptime("14 May 2014", '%d %b %Y')
>>> print(test_date.isoformat())
2014-05-14T00:00:00
You need to use %b token instead of %m.
And for use %b token you must set a locale.
Python Documentation
import datetime
import locale
locale.setlocale(locale.LC_ALL, 'fr_FR')
test_date = datetime.datetime.strptime("14 Mai 2014", '%d %b %Y')
iso_date = test_date.isoformat()
The result will be '2014-05-14T00:00:00'

Parsing string into datetime in Python

I have a date with this format
October 14, 2014 1:35PM PDT
I have this in my python script
import time
u_date = 'October 14, 2014 1:35PM PDT'
print time.strptime(u_date,"%b %d, %y %I:%M%p %Z")
I got this error as a result
ValueError: time data u'October 14, 2014 1:35PM PDT' does not match format '%b %d, %y %I:%M%p %Z'
Can anyone explain to me why is this happening? I'm new to python and any help will be appreciated.
Your format is incorrect; %b takes an abbreviated month, but you have a full month, requiring %B, and you have a full 4-digit year, so use %Y, not %y.
The time library cannot parse timezones, however, you'll have to drop the %Z part here and remove the last characters for this to work at all:
>>> time.strptime(u_date[:-4], "%B %d, %Y %I:%M%p")
time.struct_time(tm_year=2014, tm_mon=10, tm_mday=14, tm_hour=13, tm_min=35, tm_sec=0, tm_wday=1, tm_yday=287, tm_isdst=-1)
You could use the dateutil library instead to parse the full string, it'll produce a datetime.datetime object rather than a time struct:
>>> from dateutil import parser
>>> parser.parse(u_date)
datetime.datetime(2014, 10, 14, 13, 35)

Categories

Resources