1

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

My primary issue is extracting the date_modified information from the returned query.
Does the list has just one element? or more? If it has more, can you please share some? That'll give me a better idea.
The list only has the one element as shown in my original post.
I know that I can do this: 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(test)), but I was wondering if there is another way.
I was also trying at my end. Looks like too much parsing is required for it.
0

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')

1 Comment

Is date_check already a datetime.datetime? If so, you don't need the re, just reformattedDate = date_check.strptime('%Y ...') as Mayank suggested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.