Skip to content
Fix Code Error

Converting string into datetime

March 13, 2021 by Code Error
Posted By: Oli

I’ve got a huge list of date-times like this as strings:

Jun 1 2005  1:33PM
Aug 28 1999 12:00AM

I’m going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects.

This is going through Django’s ORM so I can’t use SQL to do the conversion on insert.

Solution

datetime.strptime is the main routine for parsing strings into datetimes. It can handle all sorts of formats, with the format determined by a format string you give it:

from datetime import datetime

datetime_object = datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')

The resulting datetime object is timezone-naive.

Links:

  • Python documentation for strptime: Python 2, Python 3

  • Python documentation for strptime/strftime format strings: Python 2, Python 3

  • strftime.org is also a really nice reference for strftime

Notes:

  • strptime = “string parse time”
  • strftime = “string format time”
  • Pronounce it out loud today & you won’t have to search for it again in 6 months.
Answered By: Patrick Harrington

Related Articles

  • Why google charts is giving different output for candlestick…
  • How do I include certain conditions in SQL Count
  • coercing to Unicode: need string or buffer, NoneType found…
  • Django: ImproperlyConfigured: The SECRET_KEY setting must…
  • UnsatisfiedDependencyException: Error creating bean with…
  • How to generate JAXB classes from XSD?
  • Django GraphQL API with JWT authentication implementation…
  • How to upload a file in Django?
  • Best way to do multi-row insert in Oracle?
  • Creating a range of dates and specific time in Python

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Redirect from an HTML page

Next Post:

Easiest way to convert int to string in C++

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error