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.
Related
I have a string time :
ctime = 'Thu Sep 1 12:25:26 2022'
How can I format it to :
01 Sep 2022 12:25:26
I have tried:
ctime .strftime("%d %m %Y, %H:%M:%S")
But received:
AttributeError: 'str' object has no attribute 'strftime'
Any friend can help ?
I received the datetime in below format
timestamp = '2019-03-18 01:50:00 -0800'
and wanted to convert into datetime in python
i tried but won't able to pick the UTC offset
from datetime import datetime
from datetime import timedelta
timestamp = '2019-03-18 01:50:00 -0800'
date_format = '%Y-%m-%d %H:%M:%S %z'
d_t =datetime.strptime(timestamp,date_format)
Error i get
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/_strptime.py", line 324, in _strptime
(bad_directive, format))
ValueError: 'z' is a bad directive in format '%Y-%m-%d %H:%M:%S %z'
how to pick UTC offset in python 2.7?
Just use dateutil
from dateutil import parser
obj = parser.parse('2019-03-18 01:50:00 -0800')
print(obj)
#2019-03-18 01:50:00-08:00
Install pytz library
sudo easy_install --upgrade pytz
Import pytz to code
from datetime import datetime
from pytz import timezone
date_str = "2009-05-05 22:28:15"
datetime_obj = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S") #parse only date & time
datetime_obj_utc = datetime_obj.replace(tzinfo=timezone('UTC')) #get time zone using pytz
print datetime_obj_utc.strftime("%Y-%m-%d %H:%M:%S %Z%z")
It should help.
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 '
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')
I have date as a string in this format : Sep 07 2014
and I am willing to change it to this format dd/mm/yyyy
currently I am using this code by I recive the following error:
for l in line:
l = l.strip('\n').replace('"','')
bl_time = l.split('\t')
print bl_time
s = datetime.datetime.strptime(bl_time,"%b %d %Y")
Error:
Traceback (most recent call last):
File "/Users/Documents/scripts/whois.py", line 25, in <module>
s = datetime.datetime.strptime(bl_time,"%b %d %Y")
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data 'bl_date' does not match format '%b %d %Y'
bl_time is :
May 03 2014
Sep 05 2014
and print '"{}"'.format(bl_time) is :
"May 03 2014"
"Sep 05 2014"
Can anybody help?
Ref:
https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime
https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
You can do this:
import datetime
d = datetime.datetime.strptime("Sep 07 2014", "%b %d %Y")
print d
print d.strftime("%d/%m/%Y")
>>> dt = datetime.datetime.strptime("Sep 07 2014", "%b %d %Y")
>>> dt
datetime.datetime(2014, 9, 7, 0, 0)
>>> dt.strftime("%d/%m/%Y")
'07/09/2014'
This is converting your text string into a datetime object (utilizing strptime) and then formatting that based on your required format using strftime
I'd use the excellent python-dateutil library:
from dateutil.parser import parse
try:
parse(bl_time).strftime("%m/%d/%Y")
except:
print "could not parse %s" % bl_time