cheesus
cheesus

Reputation: 1181

Converting string (with timezone) to datetime in python

I aim to convert

stringtime = '2020-02-30 10:27:00+01:00'

so that I can compare it to

nowtime = datetime.datetime.utcnow()

using

if nowtime > stringtime:
    print(1)

I tried strptime:

datetime.datetime.strptime(stringtime, '%Y-%m-%d %H:%M:%S')

But cannot find a format specification for the timezone in the strptime documentation.

I also tried

pandas.Timestamp(stringtime)

but I get ValueError: could not convert string to Timestamp.

How can this be done?

Upvotes: 0

Views: 2810

Answers (2)

Mat-KH
Mat-KH

Reputation: 76

First of all: Your stringtime is wrong, there exists no February 30th. ;)

You can achieve what you want with dateutil:

import dateutil.parser
stringtime = '2020-03-30 10:27:00+01:00'
dateutil.parser.isoparse(stringtime)
# datetime.datetime(2020, 3, 30, 10, 27, tzinfo=tzoffset(None, 3600))

Upvotes: 1

tomgalpin
tomgalpin

Reputation: 2093

datetime.datetime.strptime(stringtime, '%Y-%m-%d %H:%M:%S%z')

Will give you the expected result %z is the format (Python3 only), however your original date is invalid as February doesnt have 30 days :)

Upvotes: 2

Related Questions