0

I want to retrieve time in the format of "HH:MM" from datetime.timedelta object. I have a table stored in MySQL database. It has time column, which has stored the time in the format,

00:00:00

I have connected to MySQL server using PyMySQL module,

conn = pymysql.connect("localhost", "root", "cloudera", "streaming")
cursor = conn.cursor()
sql = "select * from table1 limit 5;"
cursor.execute(sql)
row = cursor.fetchone()
row[1]

Output is,

datetime.timedelta(0)

I have been through this post Python: How do I get time from a datetime.timedelta object?. But the difference from that question and mine is in output result. For that post, output is

datetime.timedelta(0, 64800)

And for me it is just,

datetime.timedelta(0)

I just don't get it why the output for me is that way. Can anyone please help me in retrieving time. Thanks in advance.

  • timedelta(0) would mean 0 days, 0 seconds, so you would want 00:00 – Richard Nov 03 '17 at 08:01
  • Oh! But later in the table there are entries like "23:00". So, how would that be addressed from datetime module? –  Nov 03 '17 at 08:14
  • what is the datatype for this column with "23:00" ? – Richard Nov 03 '17 at 08:16
  • paste the output of the following mysql command: show columns from table1 – Richard Nov 03 '17 at 08:26
  • `date | time | id | name | count | +------------+----------+-----------+----------------------------+--------------+ | 2009-05-01 | 23:00:00 | 4 | Town Hall (West) | 1592 ` Datatype for Time given in MySQL is "Time". For this output, output in python is `datetime.timedelta(0, 82800)` –  Nov 03 '17 at 08:49

1 Answers1

0

When you type row[1] python prints the repr of the variable - in this case repr of a timedelta is "datetime.timedetla(days, seconds)".

You can stringify it using str but that would give you HH:MM:SS

str(row[1]) 
-> "23:00:00"

To get HH:MM you can do the following:

(datetime.min + row[1]).strftime("%H:%M")
-> "23:00"

So your code should look like this:

conn = pymysql.connect("localhost", "root", "cloudera", "streaming")
cursor = conn.cursor()
sql = "select * from table1 limit 5;"
cursor.execute(sql)
row = cursor.fetchone()

timestr = (datetime.min + row[1]).strftime("%H:%M")
print(timestr)
Richard
  • 2,994
  • 1
  • 19
  • 31