Knowledge Base

Preserving for the future: Shell scripts, AoC, and more

Python3: convert relative date to UTC timestamp

I needed to convert a relative time string, e.g., "Yesterday at 3:08 am," to a UTC timestamp. Apparently this is not that easy to find on the Internet. My research combines at least 3 different sources to accomplish my goal. My incoming timezone is UTC-0500 ("US/Eastern"). And I realize it is unfortunate that I am doing some string-to-ints and back and forth. Well, please share how you could do better!

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#!/usr/bin/env python3
from datetime import timedelta
from parsedatetime import Calendar
from pytz import timezone

indate = "Yesterday at 3:08 am"
print("indate:",indate)

# long version, for explanation
cal = Calendar()
dto, _ = cal.parseDT(datetimeString=indate, tzinfo=timezone("US/Eastern"))
add_hours = int((str(dto)[-6:])[:3])
outdate = (timedelta(hours=-add_hours) + dto).strftime('%Y-%m-%dT%H:%M:%SZ')
print("outdate:",outdate)

# short form
dto, _ = Calendar().parseDT(datetimeString=indate, tzinfo=timezone("US/Eastern"))
outdate = (timedelta(hours=-int((str(dto)[-6:])[:3])) + dto).strftime('%Y-%m-%dT%H:%M:%SZ')
print("outdate:",outdate)

Sample run

$ ./sample.py 
indate: Yesterday at 3:08 am
outdate: 2020-02-02T08:08:00Z
outdate: 2020-02-02T08:08:00Z

References

Weblinks

  1. python - Convert relative date string to absolute date - Stack Overflow
  2. bear/parsedatetime: Parse human-readable date/time strings [github.com]
  3. python - Convert UTC datetime string to local datetime - Stack Overflow

Comments