从字符串到日期时间,查看当前(本地)时间 [英] From string to datetime, looking at the current (local) time

查看:78
本文介绍了从字符串到日期时间,查看当前(本地)时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中,是否有任何函数可以从字符串中提取时间信息以从当前本地时间中获取时间?例如:

Is there any function, in python, that extracts time information from a string to get the time from the current local one? For example:

我有一栏中有过去时间与当前时间相比的时间信息(比方说英国时间,大约是20:00)

I have a column with time information in the past compared to the current time (let's say UK time, approximately 20:00)

Time

10 hours # ago
6 hours # ago
12 hours # ago
2 days # ago
1 day # ago

我想看看英国目前的时间(即大约20:00):

I would like to have, looking at the current UK time, (i.e., approximately 20:00):

New_Time

10:00 
14:00 
8:00
48:00
24:00

上面的列来自当前本地时间减去 Time 列中的小时数(从字符串到数字).

The column above comes from the current local time minus the number of hours (from string to numerical) in Time column.

我可以使用某个功能吗? New_Time 是我需要的输出.

Is it something that I might do with a function? The New_Time is the output that I will need.

如果python中可能没有函数,我的方法是:

In case there might not be a function in python, my approach would be:

  • 使用一些东西来检测当前时间(将其保存在变量中)
  • 将小时数设为60分钟,将1天的时间设为24小时...为了运行一些数学运算,一旦将字符串转换为数值
  • 从当前时间中减去要返回的分钟/小时数

推荐答案

您可以使用dateparser 软件包(注释中的一些解释):

You can make use of the dateparser package (some explanation in comments):

import datetime
import dateparser # pip install dateparser

# a function to format timedelta to string needed below,
# see https://stackoverflow.com/q/538666/10197418
def timedelta2str(sec):
    hours, remainder = divmod(sec, 3600)
    return f'{int(hours):02}:{int(remainder//60):02}'

def formatTimeAgo(string, reftime):
    # try to parser... if successful, you get a datetime object
    dtobj = dateparser.parse(string, settings={'RELATIVE_BASE': reftime})
    if isinstance(dtobj, datetime.datetime):
        # calculate a timedelta object against reference time
        td = reftime - dtobj
        # now format output based on input (days or hours..)
        if td >= datetime.timedelta(1):
            return timedelta2str(td.total_seconds())
        else:
            return (reftime-td).strftime('%H:%M')
    else:
        return "N/A"

# exemplary input
t = ("10 hours", "6 hours", "2 days", "1 day")
# a reference time
reftime = datetime.datetime(2021,4,10,20)
for elem in t:
    print(elem, '->', formatTimeAgo(elem, reftime))
       
# giving you
>>> 10 hours -> 10:00
>>> 6 hours -> 14:00
>>> 2 days -> 48:00
>>> 1 day -> 24:00

现在您可以调整它以在pandas.Series上使用:

Now you can adjust that to be used on pandas.Series:

import pandas as pd

df = pd.DataFrame({'Time': ["10 hours", "6 hours", "12 hours", "2 days", "1 day"]})

df['New_Time'] = df['Time'].apply(formatTimeAgo, args=(reftime,))

df['New_Time']
0    10:00
1    14:00
2    08:00
3    48:00
4    24:00
Name: New_Time, dtype: object

这篇关于从字符串到日期时间,查看当前(本地)时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆