vishal
vishal

Reputation: 1874

Converting offset of datetime in Python 3.6

I have researched enough before posting this and I know there are a ton of a similar questions but none of them has a solid or uniform solution and also my case is slightly different.

My case is simple. I have the following value 2019-07-31 12:02:35+00:00 stored in a variable. I want to split the hours part alone out of it. this can be done using "strptime" and I tried the following method onlytime = datetime.datetime.strptime(str(dateandtime), "%Y-%m-%d %H:%M:%S%z") But I was displayed with the following error

"ValueError: time data '2019-07-31 12:02:35+00:00' does not match format '%Y-%m-%d %H:%M:%S%%z'"

%z should be working with pyhton 3.2 and above so that should not be the problem.I also tried date-utils() but the docs were confusing and I couldn't find a way to use them properly here. So what can be done here to achieve my use case? Below is my entire code:

#!/usr/bin/env python3
import boto3
from datetime import date, datetime, timedelta
import datetime
inputdata = boto3.client('s3')
details = inputdata.list_objects_v2(Bucket='testbucket')
for timedetails in details['Contents']:
    dateandtime = timedetails['LastModified']
    onlytime = datetime.datetime.strptime(str(dateandtime), "%Y-%m-%d %H:%M:%S%z")
    print (onlytime)

UPDATE: The same program is working in online compilers when I execute the datetime part alone. So I'm adding some more details about the input JSON: This is the JSON stored in the variable details

{
'Contents': [{
        u 'LastModified': datetime.datetime(2019, 7, 31, 12, 2, 35, tzinfo = tzlocal()),
        u 'ETag': '"1a8f23054d922eff88a644bd003e6397"',
        u 'StorageClass': 'STANDARD',
        u 'Key': u 'EVNET- task & window.docx',
        u 'Size': 783570
    }
}

However when I print the value stored in dateandtime it is displayed as 2019-07-31 12:02:35+00:00. I'm not sure whether these details could mean something but.

Upvotes: 2

Views: 511

Answers (2)

tinyhare
tinyhare

Reputation: 2401

Changed in version 3.7: When the %z directive is provided to the strptime() method, the UTC offsets can have a colon as a separator between hours, minutes and seconds. For example, '+01:00:00' will be parsed as an offset of one hour. In addition, providing 'Z' is identical to '+00:00'.

it seems that python 3.6 only support +0000, no colon

https://docs.python.org/3.7/library/datetime.html#strftime-and-strptime-behavior

how about this:

import datetime
import re
regex = r"([+-])([0-9]{2}):([0-9]{2})"
subst = "\\1\\2\\3"
dateandtime = "2019-07-31 12:02:35+00:00"
dateandtime = re.sub(regex, subst, dateandtime, 0)
print(dateandtime)
onlytime = datetime.datetime.strptime(str(dateandtime),"%Y-%m-%d %H:%M:%S%z")
print(onlytime)

Upvotes: 3

Kurtis Streutker
Kurtis Streutker

Reputation: 1317

The problem is UTC offsets. The RFC 3339 Internet Date/Time Format requires that every date-time includes a UTC offset, and that those offsets can either be Z (short for "Zulu time") or in +HH:MM or -HH:MM format, like +05:00 or -10:30.

Consequently, these are all valid RFC 3339 datetimes:

2008-09-03T20:56:35.450686Z
2008-09-03T20:56:35.450686+05:00
2008-09-03T20:56:35.450686-10:30

Alas, the format strings used by strptime and strftime have no directive that corresponds to UTC offsets in RFC 3339 format. You need to use a third party library or parse without the offset.

Helpful link

Upvotes: 1

Related Questions