Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert datetime in Python list to year only

Tags:

python

pyodbc

So I'm using pyodbc to take a Date Time field from MS Access add to a Python list. When I do this, it pyodbc instantly converts the data to this format datetime.datetime(2012, 1, 1,0,0). I'm only interested in obtaining the year 2012 in this case. How can I parse the year out of my List when it uses this format? Maybe pyodbc has some syntax I could use before it evens gets into the List?

like image 710
wilbev Avatar asked May 16 '12 18:05

wilbev


People also ask

How do I get month and Year in Python?

import datetime; today = str(datetime. date. today()); curr_year = int(today[:4]); curr_month = int(today[5:7]); This will get you the current month and year in integer format.

How do I get the current year in Python?

To get the current year in Python, first we need to import the date class from the datetime module and call a today(). year on it. The year property returns the current year in four-digit(2021) string format according to the user's local time.


2 Answers

You can grab the year from each of the datetime objects and form a new list.

years = [x.year for x in your_list]
like image 31
msvalkon Avatar answered Sep 30 '22 15:09

msvalkon


>>> dt = datetime.datetime(2012, 1, 1,0,0)
>>> dt.year
2012

Just for the record, datetime.datetime is not a "list of values", it's a class.

like image 183
juliomalegria Avatar answered Sep 30 '22 13:09

juliomalegria