LoginSignup
0
1

More than 3 years have passed since last update.

Python で "n 日前" と基準日から日付を得るメモ

Posted at

背景

"5 days 12 hours ago" みたいな文字列と, 基準日から, 実際の日付を得たい.

ぺろっと文字列渡してよろしく処理してくれるライブラリは無いようです.

方法

のように, 自前でパースして, dateutilrelativedelta で差分計算します.

re はめんどいので, {} でパースできる parse を使います.

from dateutil.relativedelta import relativedelta
from datetime import datetime
import parse

def ago_do_date(ago, ref_date):
    p = parse.parse('{} days {} hrs ago', ago)
    print(p)

    delta = relativedelta(days=int(p[0]), hours=int(p[1]))
    print(ref_date - delta)

print(datetime.now())
s = "16 days 16 hrs ago"
ago_do_date(s, datetime.now())
2021-04-14 18:29:29.754215
<Result ('16', '16') {}>
2021-03-29 02:29:29.754248

Voila!

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1