Python Forum
Extracting year from a string using strptime and datetime builtin
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Extracting year from a string using strptime and datetime builtin
#1
I’m trying to extract the year from a date of a string. One way of doing it would be to use string slicing which is easy and obvious. But I am trying to learn how to extract a year using timedate and strptime().

For example, given a string such as ‘8 Aug, 2015’, I am trying to convert it to a tuple using the strptime() built-in by formatting it with %d %b,%Y and then pull the year off and return it when the function is called.

Here is my script:

from datetime import datetime

def extract_year(date_parm):
   date_string_obj = datetime.strptime(date_parm, "%d %b %Y")
   year_obj = date_string_obj[2]
   return year_obj

print(extract_year('8 Aug 2015'))
Here is my traceback:
Error:
$ python basic_dt_convert.py Traceback (most recent call last): File "basic_dt_convert.py", line 8, in <module> print(extract_year('8 Aug 2015')) File "basic_dt_convert.py", line 5, in extract_year year_obj = date_string_obj[2] TypeError: 'datetime.datetime' object is not subscriptable
The traceback is pointing to line 5 when I am trying to assign the second item in the newly created tuple to a variable. The ‘TypeError: 'datetime.datetime' object is not subscriptable’ means that the date_string_obj can’t be indexed. But my understanding is that date_string_obj should be a tuple which, even though it is immutable, it is still an iterable type so with [2], Python should still be pulling the 3rd index position and assigning it to ‘year_obj’. I’m missing something here.

Could someone clarify what this trace back is saying?

What is a better way of extracting the year from a date given a string using strptime (instead of string slicing)?

I tried replacing line 5 with: year_obj = datetime.date_string_obj.year() so my script now looks like this:
 from datetime import datetime

def extract_year(date_parm):
   date_string_obj = datetime.strptime(date_parm, "%d %b %Y")
   year_obj = datetime.date_string_obj.year()
   return year_obj

print(extract_year('8 Aug 2015'))
Now Python is throwing an attribute error at line 5. How do I properly extract the year?

Resources that I have used so far:
Reply
#2
The datetime object you assign on line 4 is not a tuple. You don't extract the elements from it by numeric index like a list or tuple.

Instead you either access the attributes of the object (like .year) to pull the individual bits, or you use strftime() to format it it how you want.

from datetime import datetime
d = datetime.strptime('8 Aug 2015', "%d %b %Y")

print(f"The returned item is of type {type(d)}")
print(d.year)  # extracts year as an int
print(d.strftime("%Y")) # extracts year as a string
Output:
The returned item is of type <class 'datetime.datetime'> 2015 2015
Reply
#3
Thank you @bowlofred, this helps tremendously. Big Grin

For my future reference, the strptime method is used for “parsing” (which is what the ‘p’ stands for) a date passed in as a string while the strftime method is used to convert a date object into string “formatting” (which is what the ‘f’ stands for). To support this point of clarity, I found an answer on Stack Overflow: “What is the difference between strptime and strftime -python 3”. Interestingly, even the Ruby language has a similar datetime builtin with the two class methods of the exact same name. More details can be found at the SO question and answer titled: “How to understand strptime vs. strftime”.

One last thing, bowlofred: At your line 5, why does print(d.year) produce the desired output while print(d.year()) does not work? The subtle distinction between either statement are the parentheses when calling the year/year() class method. Why does the year class method process successfully without the ()? I ask because in my mind I thought class methods when called always require (). Could someone clarify why () is unnecessary for pulling the year in bowlofred's example script at line 5?
Reply
#4
Because year is not a method, it's an attribute (or field). Why did you think year was a method of the datetime class? The docs tell you that it's an attribute.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  subtract 2 datetime string jss 4 706 Oct-19-2023, 02:42 PM
Last Post: Larz60+
Question Extracting Version Number from a String britesc 2 1,030 May-31-2023, 10:20 AM
Last Post: britesc
  Trying to get year not the entire year & time mbrown009 2 862 Jan-09-2023, 01:46 PM
Last Post: snippsat
  String formatting (strptime) issues Henrio 2 811 Jan-06-2023, 06:57 PM
Last Post: deanhystad
  TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'str' findbikash 2 9,512 Sep-18-2019, 08:32 AM
Last Post: buran
  Convert String to Datetime Object tkj80 2 33,696 Apr-20-2017, 08:45 AM
Last Post: volcano63

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020