R
R
r4khic2019-09-20 12:27:40
Python
r4khic, 2019-09-20 12:27:40

How to trim the date?

I'm trying to trim such a date "2019-09-20 08:15:15+00:00" to be like this "2019-09-20 08:15:15" for this there is such a piece of code:

from goose3 import Goose
import dateparser

g = Goose()
article_date = g.extract(url='http://stavropol-news.net/society/2019/09/20/20319.html').publish_date
date_parsed = dateparser.parse(article_date)

if len(date_parsed.split(" ")) > 4:
    data = " ".join(date_parsed.split(" ")[:4])
    print(data) # Вывод должен быть таким 2019-09-20 08:15:15

It would seem that the code should work, but there is no error. As I understand from the error , the datetime.datetime object does not have a split attribute , and because of this, such an error.
Traceback (most recent call last):
File "C:PycharmProjects/parser_russian_resource/goose.py", line 8, in
if len(date_parsed.split(" ")) > 4:
AttributeError: 'datetime.datetime' object has no attribute 'split'

Question: Is it possible to somehow convert 'datetime.datetime' to a valid string?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Yakushenko, 2019-09-20
@r4khic

You're trying to truncate a datetime object, not a string, and you can't do that. You need to convert the datetime object to a string of the form you need:

date_parsed = dateparser.parse(article_date)
date_string = date_parsed.strftime('%Y-%m-%d %H:%M:%S')
print(date_string)
>>> '2019-09-20 08:15:15'

strftime()You can read about arguments for here .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question