【问题标题】:Convert timestamp to time only仅将时间戳转换为时间
【发布时间】:2019-12-06 16:12:51
【问题描述】:

我从 Outlook 获取日历结果,仅获取每个日历项的开始时间和主题。

import win32com, win32com.client
import datetime, time, pytz

def getCalendarEntries():
    Outlook      = win32com.client.Dispatch("Outlook.Application")
    appointments = Outlook.GetNamespace("MAPI").GetDefaultFolder(9).Items
    appointments.Sort("[Start]");
    appointments.IncludeRecurrences = "True"
    today    = datetime.datetime.today().date().strftime("%Y-%d-%m")
    tomorrow = (datetime.date.today() + datetime.timedelta(days=1)).strftime("%Y-%d-%m")
    appointments = appointments.Restrict("[Start] >= '" +today+"' AND [Start] < '"+tomorrow+"'");
    events={'Start':[],'Subject':[]}
    for a in appointments: 
        events['Start'  ].append(a.Start  );
        events['Subject'].append(a.Subject)
    return events

calendar = getCalendarEntries();

n=len(calendar['Start']);
i=0;

while( n ):
    print(
        calendar['Start'][i]  , 
        calendar['Subject'][i]
    );
    n-=1;
    i+=1; 

这是结果,而且是正确的:

$ py test_outlook.py
2019-12-06 10:00:00+00:00 test apointment 

我现在需要处理上面的数据以仅获取时间:10:00,这样我就可以进行计算并找出距离活动开始还有多少时间......就像距离 10 分钟一样, 1 小时后,等等。

我真的不知道该怎么做……有人知道吗?

【问题讨论】:

    标签: python


    【解决方案1】:

    Uri Goren 似乎在这里回答了这个问题:https://stackoverflow.com/a/38992623/8678978

    你需要使用带有日期时间格式的strptime来获取一个日期对象,然后你可以提取时间部分。

    dateString = '2019-12-06 10:00:00+00:00'
    dateObject = datetime.datetime.strptime(str[0:19], '%Y-%m-%d %H:%M:%S')
    

    现在您有了一个日期对象,并且可以使用以下方法获取时间部分:

    dateObject.hour
    dateObject.minute
    dateObject.second
    

    【讨论】:

      【解决方案2】:

      我不确定getCalendarEntries 返回的类型。您可以通过在程序中添加额外的临时行来查找:

      print(type(calendar['Start'][i]))
      

      如果是datetime对象,可以简单查询hour属性:

      hours = calendar['Start'][i].hour
      

      如果getCalendarEntries返回一个POSIX时间戳,可以先转换成Python datetime对象,然后查询小时

      dt = datetime.fromtimestamp(calendar['Start'][i])
      hours = dt.hour
      

      如果是字符串,可以使用datetime.fromisoformat解析:

      dt = datetime.datetime.fromisoformat(calendar['Start'][i])
      hours = dt.hour
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-20
        • 2019-07-07
        • 2018-12-02
        • 2013-04-07
        • 2011-01-15
        相关资源
        最近更新 更多