Life is complex
Life is complex

Reputation: 15629

Extract and reformat PostgreSQL query output (python)

I'm querying a PostgreSQL database with asyncpg. My query is checking a table to determine if a specific record number exist. If the record exist then the date_modified information is extracted from that record, which I need to compare with a newly collected date.

My current issue is trying to extract the timestamp information from the list, which is returned by the query, which is shown below:

[<Record date_modified=datetime.datetime(2010, 9, 9, 8, 33, 31)>]

The only way that I have found to obtain the date string is with a regex.

 date_modified = re.search(r'(\d{4},\s\d{1,2},\s\d{1,2},\s\d{1,2},\s\d{1,2},\s\d{1,2})',  repr(date_check))

 print (date_modified.group(0))

 outputs: 2010, 9, 9, 8, 33, 31

How do I convert the output above to this format?

2010-09-09 08:33:31

Upvotes: 1

Views: 190

Answers (2)

Life is complex
Life is complex

Reputation: 15629

I solved this problem by doing this:

date_modified = re.search(r'(\d{4},\s\d{1,2},\s\d{1,2},\s\d{1,2},\s\d{1,2},\s\d{1,2})',  repr(date_check))
reformattedDate = datetime.datetime.strptime(date_modified.group(0), '%Y, %m, %d, %H, %M, %S').strftime('%Y-%m-%d %H:%M:%S')

Upvotes: 0

Mayank Porwal
Mayank Porwal

Reputation: 34086

Try this:

import datetime

In [1465]: datetime.datetime.strftime(date_modified,'%Y-%m-%d %H:%M:%S')
Out[1465]: '2010-09-09 08:33:31'

Read the doc strftime for more info.

Upvotes: 2

Related Questions