Reputation: 5800
I am using the following piece of code to populate my database. I've imported from datetime import datetime
and is trying to create a datetime object to save to the DateTimeField of django.
with open(os.path.join(settings.BASE_DIR, 'media', 'attendance', 'populate.csv')) as f:
reader = csv.reader(f)
for row in reader:
obj, created = Attendance.objects.get_or_create(
employee_id=row[0],
punch=datetime.strptime(row[1], "%Y%m%d %H%M"),
)
This is the error that I get.
ValueError at /attn/populate/
time data ' 20170604 0600' does not match format '%Y%m%d %H%M'
It seems like the string DOES match the format. What am I doing wrong here?
Upvotes: 0
Views: 346
Reputation: 81604
The string is ' 20170604 0600'
, note the leading whitespace.
Change the format to ' %Y%m%d %H%M'
, or use strip
to remove any leading or trailing spaces from the string:
for row in reader:
obj, created = Attendance.objects.get_or_create(
employee_id=row[0],
punch=datetime.strptime(row[1].strip(), "%Y%m%d %H%M"))
Upvotes: 2
Reputation: 2523
Extra leading space in string
from datetime import datetime
print(datetime.strptime(" 20170604 0600", " %Y%m%d %H%M"))
print(datetime.strptime("20170604 0600", "%Y%m%d %H%M"))
Upvotes: 1