How to create datetime object from "16SEP2012" in python

Question:

I can create datetime objects in python this way:

import datetime

new_date= datetime.datetime(2012,09,16)

How can I create same datetime object from a string in this format: "16SEP2012" ?

Asked By: alwbtc

||

Answers:

Use datetime.datetime.strptime:

>>> datetime.datetime.strptime('16Sep2012', '%d%b%Y')
datetime.datetime(2012, 9, 16, 0, 0)
Answered By: falsetru

One additional thing to add here- DateTime Formats

@falsetru’s answer is all good and correct as per what OP asked, though I do feel there’s a need to mention DateTime Formats.

So this part inside the function- '%d%b%Y', which is given as a parameter, denotes DateTime format codes. You can access all the types from this link. The table that mentions all the types is towards the bottom of the webpage.

So for example if we need to get a DateTime object for a particular date in a string format. Let’s say:

>>> date = 'Sat 02 May 2015 19:54:36 +0000'

The format code would go something like:

>>> from datetime import datetime
>>> date_now = datetime.strptime(date, '%a %d %b %Y %X %z')
>>> print(date_now)
2015-05-02 19:54:36+05:30

NOTE: Since there was space between the string values, I am giving space as well. If there’s let’s a hyphen(-), you can give that instead:

>>> date1 = '22-May-2015 19:54:36'
>>> print(datetime.strptime(date1, '%d-%b-%Y %X'))
2015-05-22 19:54:36

Now once you convert strings into datetime objects, you can perform plethora of things on them. One good example is, like finding the difference between two dates:

>>> date1 = 'Sat 02 May 2015 19:54:36 +0530'
>>> date2 = 'Fri 01 May 2015 13:54:36 -0000'

>>> first = datetime.strptime(date1, '%a %d %b %Y %X %z')
>>> second = datetime.strptime(date2, '%a %d %b %Y %X %z')

>>> diff = first - second
>>> print(diff.total_seconds())
88200.0

I’ve used this answer multiple times but I usually always had to google for other datetime formats. I hope this would be helpful to someone else as well.

Answered By: Amit Amola
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.