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!


#!/usr/bin/env python3
from datetime import timedelta
from parsedatetime import Calendar
from pytz import timezone 

indate = "Yesterday at 3:08 am"

# 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')

# 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')

Sample run

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



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

2 thoughts on “Python3: convert relative date to UTC timestamp

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.