将气流宏“ts”转换为日期时间对象

Ale*_* Ho 5 python datetime-format airflow

我在将气流宏引用“ts”转换为日期时间对象时遇到问题。问题出在字符串末尾的tz上。

from datetime import datetime
timetoday = kwargs['ts']
t = datetime.strptime(timetoday, '%Y-%m-%dT%H:%M:%S%z')
Run Code Online (Sandbox Code Playgroud)

代码没有成功执行,而是抛出错误消息:

time data '2019-08-24T00:00:00+00:00' does not match format '%Y-%m-%dT%H:%M:%S%z'
Run Code Online (Sandbox Code Playgroud)

如果我使用格式略有不同的相同代码,并尝试使用“ds”宏,并且我设法将字符串转换为日期时间对象。

time data '2019-08-24T00:00:00+00:00' does not match format '%Y-%m-%dT%H:%M:%S%z'
Run Code Online (Sandbox Code Playgroud)

更新:阅读http://strftime.org/中的注释并了解其%z格式为+HHMM-HHMM的 UTC 偏移量(如果对象是幼稚的,则为空字符串)。':'这让我想知道之间的附加+00:00(返回的字符串 ofkwargs['ts']是否是错误的根本原因。但是,我仍然不确定如何正确解析它,因为strptime.

因此,我将宏更改为kwargs['ts_nodash']不返回时区,并暂时继续我的代码。如果有人知道如何做到这一点,我仍然有兴趣了解如何正确完成!谢谢!

from datetime import datetime
timetoday = kwargs['ds']
t = datetime.strptime(timetoday, '%Y-%m-%d')
Run Code Online (Sandbox Code Playgroud)

y2k*_*ham 5

查看宏参考,然后查看您的用例,我建议您使用execution_date宏而不是ts

{{ ts }}            : same as execution_date.isoformat(). Example: 2018-01-01T00:00:00+00:00

{{ execution_date }}: the execution_date (pendulum.Pendulum)
Run Code Online (Sandbox Code Playgroud)

如果你同意的话,这一切都可以归结为execution_date钟摆对象转换为 Pythondatetime对象,这很简单datetime.fromtimestamp(execution_date.timestamp())

Python 片段(转换)演示:

import pendulum
from pendulum import Pendulum
from datetime import datetime
..
execution_date: Pendulum = pendulum.now()
execution_date_as_datetime: datetime = datetime.fromtimestamp(execution_date.timestamp())
Run Code Online (Sandbox Code Playgroud)

参考