-1

How to convert AWSTimestamp into python DateTime?

I am using AWS AppSync scalar type AWSTimestamp for datetime

Example:

2021-02-02T16:00:00-07:00

How to convert the above format to python datetime?

Thirumal
  • 8,280
  • 11
  • 53
  • 103
  • 2
    This is ISO format with timezone. Default datetime module handles it well - https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat (click for specific classmethod and examples!) – h4z3 Jul 14 '21 at 09:13
  • Getting this error ` AttributeError: type object 'datetime.datetime' has no attribute 'fromisoformat'` – Thirumal Jul 14 '21 at 09:15
  • What python version? – h4z3 Jul 14 '21 at 09:18
  • version -> Python 3.6.9 – Thirumal Jul 14 '21 at 09:20
  • 1
    "New in version 3.7." 1. Consider updating. 2. Check if you have dateutils - it's external package but commonly comes preinstalled as it's really useful. `from dateutil.parser import isoparse` (https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.isoparse) or just `parse` (https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.parse) – h4z3 Jul 14 '21 at 09:25
  • Does this answer your question? [How do I parse an ISO 8601-formatted date?](https://stackoverflow.com/questions/127803/how-do-i-parse-an-iso-8601-formatted-date) – FObersteiner Jul 14 '21 at 09:31
  • `ValueError: time data '2021-02-02T16:00:00-07:00' does not match format '%Y-%m-%dT%H:%M:%S.Z'`. dateutil.parser.isoparse('2021-02-02T16:00:00-07:00 ') worked – Thirumal Jul 14 '21 at 09:39
  • 1
    @Thirumal your parsing directive is wrong; please have another look at [the docs](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior). Correct would be `'%Y-%m-%dT%H:%M:%S%z'` - but I suspect you'll require a newer version of Python to make this work. – FObersteiner Jul 14 '21 at 09:57

2 Answers2

0

Try this - datetime.strptime(date_s, '%Y-%m-%dT%H:%M:%S+00:00')

0
import dateutil.parser
dt = dateutil.parser.isoparse('2021-02-02T16:00:00-07:00')
Thirumal
  • 8,280
  • 11
  • 53
  • 103