HansDampf
HansDampf

Reputation: 121

How do I modify the format of a date string? (Python/Excel)

what is the best method in Python to convert a string to a given format? My problem is that I have scraped dates that have the following format: Dec 13, 2019 6:01 am

Ideally I want to analyse the scraped data in excel, but unfortunately Excel can not read this date format.

Do you think it is best to do that in Python or in Excel?

Thanks

Upvotes: 0

Views: 1391

Answers (3)

Myke Bilyanskyy
Myke Bilyanskyy

Reputation: 678

You can definetely do this with Python using either standard library, or dateparser package.

>>> import dateparser
>>> dateparser.parse('Dec 13, 2019 6:01 am')
datetime.datetime(2019, 12, 13, 6, 1)

Or directly to ISO format:

>>> dateparser.parse('Dec 13, 2019 6:01 am').isoformat()
'2019-12-13T06:01:00'

Another thing to look out for when working with time programmatically is time zone - it's where bugs are very likely to appear. There's a very sweet package for working with datetime data in python called pendulum, I cannot stress enough how convenient it is. And it's API is completely compatible with python's standard library datetime. So you can just do import pendulum as dt instead of import datetime as dt and it will work.

It also has a great parser tool with support for time zones:

>>> import pendulum

>>> dt = pendulum.parse('1975-05-21T22:00:00')
>>> print(dt)
'1975-05-21T22:00:00+00:00

# You can pass a tz keyword to specify the timezone
>>> dt = pendulum.parse('1975-05-21T22:00:00', tz='Europe/Paris')
>>> print(dt)
'1975-05-21T22:00:00+01:00'

# Not ISO 8601 compliant but common
>>> dt = pendulum.parse('1975-05-21 22:00:00')

By passing the tz keyword argument you can parse and specify time zone at the same time.

Upvotes: 2

pennine
pennine

Reputation: 59

You can use strptime() to convert string to a datetime format.

>>> utc_time = datetime.strptime("Dec 13, 2019 6:01 am", "%b %d, %Y %I:%M %p")
>>> utc_time.strftime("%d-%m-%Y %R")
'13-12-2019 06:01'

Upvotes: 2

Faizan Naseer
Faizan Naseer

Reputation: 627

you can use pythons inbuilt datetime library.

check this: https://docs.python.org/3.6/library/datetime.html

Upvotes: 1

Related Questions