Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmedshahriar/1eae061f9192d621be7b9d6e5e5b97cc to your computer and use it in GitHub Desktop.
Save ahmedshahriar/1eae061f9192d621be7b9d6e5e5b97cc to your computer and use it in GitHub Desktop.
Code snippet to calculate exact date-time from a text using date-time denoted numbers(1,2,3,4...) and words('week', 'a week', 'day', 'hour') . Applied for some social media posts texts which denotes time such as "1 hour ago" , '3 weeks ago' etc
from datetime import datetime, timedelta
import re
'''
examples cases:
4 DAYS AGO
1 HOUR AGO
Listed 4 days ago in East Wenatchee, WA
Listed a week ago in East Wenatchee, WA
Listed an hour ago in East Wenatchee, WA
Listed 2 weeks ago in East Wenatchee, WA
'''
# txt_with_dt = "Listed a hours ago in East Wenatchee, WA"
txt_with_dt = "Listed 4 HOURS ago in East Wenatchee, WA"
def process_time(txt_with_dt):
return [s for s in txt_with_dt.lower().split() if s.isdigit() or s == 'a' or s == 'an'][0]
def timestamp_formatter(txt_with_dt):
if re.search("hour", txt_with_dt.lower()):
hours = process_time(txt_with_dt)
# for utc time use datetime.utcnow()
d = datetime.now() - timedelta(hours=int(hours) if hours.isdigit() else 1)
return d.strftime('%Y-%m-%d %H:%M:%S')
if re.search("week", txt_with_dt.lower()):
week = process_time(txt_with_dt)
d = datetime.now() - timedelta(weeks=int(week) if week.isdigit() else 1)
return d.strftime('%Y-%m-%d %H:%M:%S')
if re.search("day", txt_with_dt.lower()):
day = process_time(txt_with_dt)
d = datetime.now() - timedelta(days=int(day) if day.isdigit() else 1)
return d.strftime('%Y-%m-%d %H:%M:%S')
print(timestamp_formatter(txt_with_dt))
# output
# 2020-11-28 09:42:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment