|
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 |