0

I try to extract a date from a SQL Server Table. I get my query to return it like this:

Hours = pd.read_sql_query("select * from tblAllHours",con)

Now I convert my "Start" Column in the Hours dataframe like this:

Hours['Start'] = pd.to_datetime(Hours['Start'], format='%Y-%m-%d')

then I select the row I want in the column like this:

StartDate1 = Hours.loc[Hours.Month == Sym1, 'Start'].values

Now, if I print my variable print(StartDate1) I get this result:

[datetime.date(2020, 10, 1)]

What I need is actually 2020-10-01

How can I get this result?

Rich
  • 271
  • 1
  • 13

2 Answers2

1
  • You currently have a column of datetimes. The format you're requesting is a string format
  • Use pandas.Series.dt.strftime to convert the datetime to a string
  • pd.to_datetime(Hours['Start'], format='%Y-%m-%d'): format tells the parser what format your dates are in, so they can be converted to a datetime, it is not a way to indicate the format you want the datetime.
  • If you want only the values, not the Series, use .values at the end of the following command, as you did in the question.
start_date_str = Hours.Start.dt.strftime('%Y-%m-%d')
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
1

try

print(Hours['Start'].dt.strftime('%Y-%m-%d').values)

result is a list of YYYY-MM-dd

['2020-07-03', '2020-07-02']

a bit similar to this How to change the datetime format in pandas