python:如何转换" x天前"或者" x个月前"至今?

时间:2015-07-22 05:52:20

标签: python date

如何在python中将以下语句转换为日期(无需时间)?

 07-22 01:31:01.769: E/AndroidRuntime(27610): FATAL EXCEPTION: AsyncTask #1
07-22 01:31:01.769: E/AndroidRuntime(27610): Process: com.example.griding, PID: 27610
07-22 01:31:01.769: E/AndroidRuntime(27610): java.lang.RuntimeException: An error occured while executing doInBackground()
07-22 01:31:01.769: E/AndroidRuntime(27610):    at android.os.AsyncTask$3.done(AsyncTask.java:300)
07-22 01:31:01.769: E/AndroidRuntime(27610):    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
07-22 01:31:01.769: E/AndroidRuntime(27610):    at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
07-22 01:31:01.769: E/AndroidRuntime(27610):    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
07-22 01:31:01.769: E/AndroidRuntime(27610):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
07-22 01:31:01.769: E/AndroidRuntime(27610):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
07-22 01:31:01.769: E/AndroidRuntime(27610):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
07-22 01:31:01.769: E/AndroidRuntime(27610):    at java.lang.Thread.run(Thread.java:841)
07-22 01:31:01.769: E/AndroidRuntime(27610): Caused by: java.lang.IllegalArgumentException: position=0 count=9223372036854775807
07-22 01:31:01.769: E/AndroidRuntime(27610):    at java.nio.FileChannelImpl.transferFrom(FileChannelImpl.java:368)
07-22 01:31:01.769: E/AndroidRuntime(27610):    at com.example.myApp.DownloadManagerActivity$getUrlsClass.doInBackground(DownloadManagerActivity.java:284)
07-22 01:31:01.769: E/AndroidRuntime(27610):    at com.example.myApp.DownloadManagerActivity$getUrlsClass.doInBackground(DownloadManagerActivity.java:1)
07-22 01:31:01.769: E/AndroidRuntime(27610):    at android.os.AsyncTask$2.call(AsyncTask.java:288)
07-22 01:31:01.769: E/AndroidRuntime(27610):    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
07-22 01:31:01.769: E/AndroidRuntime(27610):    ... 4 more

以下是我目前制作的代码:

10 days ago
about 2 months ago

它奏效了,但我觉得很尴尬。

1 个答案:

答案 0 :(得分:3)

  • 使用正则表达式获取相关部分:

    value, unit = re.search(r'(\d+) (\w+) ago', 'about 2 months ago').groups()
    
  • 创建dateutil.relativedelta

    from dateutil.relativedelta import relativedelta
    if not unit.endswith('s'): unit += 's'
    delta = relativedelta(**{unit: int(value)})
    
  • 从当前日期减去它:

    from datetime import datetime
    print datetime.now() - delta
    

所以整个功能将是:

from dateutil.relativedelta import relativedelta
from datetime import datetime

def ago_do_date(ago):
    value, unit = re.search(r'(\d+) (\w+) ago', ago).groups()
    if not unit.endswith('s'):
        unit += 's'
    delta = relativedelta(**{unit: int(value)})
    print datetime.now() - delta