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
#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


Messages In This Thread
RE: Extracting year from a string using strptime and datetime builtin - by bowlofred - Aug-06-2020, 04:11 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
Question Convert UTC now() to local time to compare to a strptime() Calab 2 286 Apr-29-2024, 07:24 PM
Last Post: deanhystad
  subtract 2 datetime string jss 4 867 Oct-19-2023, 02:42 PM
Last Post: Larz60+
Question Extracting Version Number from a String britesc 2 1,154 May-31-2023, 10:20 AM
Last Post: britesc
  Trying to get year not the entire year & time mbrown009 2 917 Jan-09-2023, 01:46 PM
Last Post: snippsat
  String formatting (strptime) issues Henrio 2 897 Jan-06-2023, 06:57 PM
Last Post: deanhystad
  TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'str' findbikash 2 9,689 Sep-18-2019, 08:32 AM
Last Post: buran
  Convert String to Datetime Object tkj80 2 33,886 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