Python datetime.strptime - ValueError: time data does not match format - python

I am new in Python. I try write program who will read from file and write it to database. There is part of my code :
import datetime
format = '[%d/%b/%Y:%I:%M:%S '
mytime = '[29/Oct/2017:13:11:38 '
now = datetime.datetime.strptime(mytime, format)
When I run script I have this error :
now = datetime.datetime.strptime(mytime, format)
File "/usr/lib/python2.7/_strptime.py", line 332, in _strptime
(data_string, format))
ValueError: time data '[29/Oct/2017:13:11:38 ' does not match format '[%d/%b/%Y:%I:%M:%S '
I dont understood this mistake. It match format. There is no extra space or anything like that. And I use this 2 lines of code
format = '[%d/%b/%Y:%I:%M:%S '
now = datetime.datetime.strptime(mytime, format)
in another program and it works fine. Where is problem ?

Looking at the docs, %I matches hours for times in AM/PM format, meaning valid values range from 01 to 12. You have 13 (1 PM)
I guess you need to use %H
import datetime
mytime = '[29/Oct/2017:13:11:38 '
fmt = '[%d/%b/%Y:%H:%M:%S '
now = datetime.datetime.strptime(mytime, fmt)
print("now: %s" % now.strftime('%Y-%m-%d %H:%M:%S'))
prints:
now: 2017-10-29 13:11:38
Check this:
fmt = '[%d/%b/%Y:%I:%M:%S '
for test in range(1, 24):
mytime = '[29/Oct/2017:%02d:11:38 ' % test
now = datetime.datetime.strptime(mytime, fmt)
print("now: %s" % now.strftime('%Y-%m-%d %H:%M:%S'))
Will work "fine" (I quote because 12 is assumed to be midnight) until test hits 13:
now: 2017-10-29 01:11:38
now: 2017-10-29 02:11:38
now: 2017-10-29 03:11:38
now: 2017-10-29 04:11:38
now: 2017-10-29 05:11:38
now: 2017-10-29 06:11:38
now: 2017-10-29 07:11:38
now: 2017-10-29 08:11:38
now: 2017-10-29 09:11:38
now: 2017-10-29 10:11:38
now: 2017-10-29 11:11:38
now: 2017-10-29 00:11:38
Traceback (most recent call last):
File "./stack_096.py", line 12, in <module>
now = datetime.datetime.strptime(mytime, fmt)
File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/_strptime.py", line 500, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/_strptime.py", line 337, in _strptime
(data_string, format))
ValueError: time data '[29/Oct/2017:13:11:38 ' does not match format '[%d/%b/%Y:%I:%M:%S '

Related

ValueError: unconverted data remains: 00:00:00

I have problem in convert date time.
Here is my code:
#api.multi
def action_confirm(self):
if picking.state not in ['cancel', 'draft']:
for schedule_delivery in sorted_key:
print "line 105: ", schedule_delivery
dup_picking = picking.copy()
if shift == "afternoon":
date_object = datetime.strptime(schedule_delivery, '%Y-%m-%d')
print "Line 146", date_object
# raise EnvironmentError
tanggal = datetime.strftime(date_object, "%Y-%m-%d") + ' 06:00:00'
print "Line 145", tanggal
dup_picking.min_date = tanggal
else:
dup_picking.min_date = schedule_delivery
Error:
date_object = datetime.strptime(schedule_delivery, '%Y-%m-%d')
File "/usr/lib/python2.7/_strptime.py", line 328, in _strptime
data_string[found.end():])
ValueError: unconverted data remains: 00:00:00
You can use this line of code-
date_object = datetime.strptime(str(schedule_delivery), '%Y-%m-%d %H:%M:%S')
i know its was asked a long time ago, i hope its still relevant.
in order to avoid the remains of the time format you need to convert your datetime to date
this is the code that solved this issue for me:
self.start_date=str((datetime.strptime(str(self.start_date), '%Y-%m-%d')+timedelta(nDays)).date())
Blockquote
Change the date to a pandas date:
Time object e.g
a = pd.to_datetime(df['date']).apply(lambda x: x.date())
Then
date_object = datetime.strptime(str(schedule_delivery), '%Y-%m-%d')

Time data format mismatch error [duplicate]

This question already has answers here:
How to preserve timezone when parsing date/time strings with strptime()?
(5 answers)
Closed 6 years ago.
I have a piece of code that currently runs without any issues on my local python (anaconda python 3.5.1) but is giving me an odd error when I run it in production (where I am under the impression the environment is very similar and the python version is the same).
Below is the relevant code snippet:
ds_date_format = "%Y%m%d"
rta_date_format = '%a %b %d %H:%M:%S %Z %Y'
d1 = datetime.datetime.strptime(date_ds, ds_date_format)
d2 = datetime.datetime.strptime(date_rta, rta_date_format).replace(hour=0, minute=0, second=0)
And the traceback for the error I am getting.
{
"error": {
"traceback": [
"Traceback (most recent call last):\n",
" File \"/opt/conda/lib/python3.5/site-packages/tornado/web.py\", line 1445, in _execute\n result = yield result\n",
" File \"/opt/conda/lib/python3.5/site-packages/tornado/gen.py\", line 1008, in run\n value = future.result()\n",
" File \"/opt/conda/lib/python3.5/site-packages/tornado/concurrent.py\", line 232, in result\n raise_exc_info(self._exc_info)\n",
" File \"<string>\", line 3, in raise_exc_info\n",
" File \"/opt/conda/lib/python3.5/site-packages/tornado/gen.py\", line 1017, in run\n yielded = self.gen.send(value)\n",
" File \"<string>\", line 6, in _wrap_awaitable\n",
" File \"rtamatching.py\", line 171, in post\n self.write(await self.rta_matcher.check_matches(data))\n",
" File \"rtamatching.py\", line 114, in check_matches\n date_match_scores.append(date_similarity(date, user_feeds[key]['TransactionDate']))\n",
" File \"/opt/api/functions.py\", line 9, in date_similarity\n d2 = datetime.datetime.strptime(date_rta, rta_date_format).replace(hour=0, minute=0, second=0)\n",
" File \"/opt/conda/lib/python3.5/_strptime.py\", line 500, in _strptime_datetime\n tt, fraction = _strptime(data_string, format)\n",
" File \"/opt/conda/lib/python3.5/_strptime.py\", line 337, in _strptime\n (data_string, format))\n",
"ValueError: time data 'Wed Mar 09 21:59:50 PST 2016' does not match format '%a %b %d %H:%M:%S %Z %Y'\n"
],
"code": 500,
"message": "Internal Server Error"
}
}
That value error seems odd to be because as far as I can tell, the format specified is correct.
As pointed out by M.T, there appears to be an issue with strptime() and timezones. Re-writing my code as follows achieved the result I was expecting:
from dateutil.parser import parse
...
d1 = parse(date_ds)
d2 = parse(date_rta)
...

Convert string to datetime to epoch

I am using Python to query a MySQL table and getting one datetime in string format, which is stored in row[3]. I need to convert this string timestamp to epoch seconds.
import MySQLdb
import os
import datetime
try:
db = MySQLdb.connect("localhost","root","","test" )
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit (1)
cursor = db.cursor()
cursor.execute ("SELECT * from main_tbl WHERE login_user_name='kumar'")
data = cursor.fetchall()
for row in data :
print row[3] ###printing 2014-09-26 12:24:23
date = datetime.datetime.strptime(row[3], "%Y-%m-%d %H:%M:%S")
print date
On execution it throws this error:
2014-09-26 12:24:23
Traceback (most recent call last):
File "test1.py", line 22, in <module>
date = datetime.datetime.strptime(row[3], "%Y-%m-%d %H:%M:%S")
TypeError: must be string, not datetime.datetime
What am I doing wrong?
I have also tried the following:
epoch_start = time.mktime(time.strptime(row[3], "%Y-%m-%d %H:%M:%S"));
But I get this error:
Traceback (most recent call last):
File "test1.py", line 29, in <module>
epoch_start = time.mktime(time.strptime(row[3], "%Y-%m-%d %H:%M:%S"));
File "C:\Python27\lib\_strptime.py", line 467, in _strptime_time
return _strptime(data_string, format)[0]
File "C:\Python27\lib\_strptime.py", line 322, in _strptime
found = format_regex.match(data_string)
TypeError: expected string or buffer
The value in row[3] is already in the datetime.datetime format as it is being clearly pointed out by the traceback. So there is no need for creating the variable date. You can use the row[3] directly as a datetime.datetime object.
Just try printing:
print type(row[3])
That should give the type as datetime.datetime
row[3] is already in datetime.datetime format.
From your question its sounds like you want convert to EPOCH
so do something like:
import time
epochTime = time.mktime(row[3].timetuple())
print epochTime
Then check if the converted epoch is correct or not:
print time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(epochTime))
print row[3]
Verify last two statements have the same output.

I'm receiving an error when formatting a date in Python, why?

This is my code for formatting a date:
def updateUserDBDates():
global userDB, currentDate, previousDate, changeInDate
index = 0
index2 = 0
userDB[1] = datetime.strptime("%d-%m-%Y", userDB[0])
userDB[0] = datetime.today().strftime("%d-%m-%Y")
saveData()
currentDate = userDB[0]
previousDate = userDB[1]
changeInDate = currentDate - previousDate
and I get this error:
File "/home/nathan/Documents/project001/programFiles/Project 001.py", line 170, in updateUserDBDates
userDB[1] = datetime.strptime("%d-%m-%Y", userDB[0])
File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data '%d-%m-%Y' does not match format '28-09-2013'
From what I can see everything should work fine, what is causing this error and how can I fix it easily?
datetime.datetime.strptime receive date_str, format as arguments (not format, date_str):
>>> import datetime
>>> datetime.datetime.strptime('28-09-2013', '%d-%m-%Y')
datetime.datetime(2013, 9, 28, 0, 0)
The argument ordering for strptime() is wrong.
http://docs.python.org/2/library/datetime.html#datetime.datetime.strptime

Python DateTime Format Error

I am new at Python. I was trying to play with time and date objects. I wrote a simple test program to parse a string into a specific time format. But its throwing a ValueError. Can you please help me out here?
Here is the code:
import time
testDate = "Tuesday, Febuary 23 2011 12:00:00 UTC"
today = time.strptime(testDate,"%A, %B %d %Y %H:%M:%S %Z")
print today
and the error:
Traceback (most recent call last):
File "D:\Python\PythonTest\src\helloWorld.py", line 3, in <module>
today = time.strptime(testDate,"%A, %B %d %Y %H:%M:%S %Z")
File "C:\Python27\Lib\_strptime.py", line 467, in _strptime_time
return _strptime(data_string, format)[0]
File "C:\Python27\Lib\_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data 'Tuesday, Febuary 23 2011 12:00:00 UTC' does not match format '%A, %B %d %Y %H:%M:%S %Z'
You had February misspelled. Your code works.
import time
testDate = "Tuesday, February 23 2011 12:00:00 UTC"
today = time.strptime(testDate,"%A, %B %d %Y %H:%M:%S %Z")
print today
Very simple: you spelled "February" wrong:
import time
testDate = "Tuesday, February 23 2011 12:00:00 UTC"
today = time.strptime(testDate,"%A, %B %d %Y %H:%M:%S %Z")
print today
Originally, you had "February" spelled as "Febuary". Works fine once that is fixed.

Categories

Resources