【问题标题】:How to get execution_date as epoch time?如何获取 execution_date 作为纪元时间?
【发布时间】:2019-04-17 05:46:15
【问题描述】:

在常规的 python 代码中我可以做到:

import time
int(time.time())

这给了我作为时代的时间。 我希望能够使用气流宏来做到这一点:execution_date

这是我尝试过的:

"{{  strptime(execution_date.strftime('%Y-%m-%d %H:%M:%S'), '%d.%m.%Y %H:%M:%S') }}"

但这给出了:

jinja2.exceptions.UndefinedError: 'strptime' 未定义

我正在运行 Airflow 1.9 和 Python 2.7

【问题讨论】:

  • 您应该先在 Python 代码中进行日期时间转换并将其值存储在变量中,然后在 Jinja 模板中渲染该变量
  • 查看自定义过滤器上的documentation

标签: python jinja2 airflow


【解决方案1】:

从 Airflow 1.10 开始,Airflow 使用 Pendulum 作为日期时间,它的属性 timestamp()int_timestampfloat_timestamp 返回纪元。

所以,你可以这样做:

{{ execution_date.int_timestamp }}

文档:https://pendulum.eustace.io/docs/#attributes-and-properties

其他选项有:

{{ execution_date.strftime('%s') }} # Also Python 2
{{ execution_date.timestamp() }}    # Python >=3.3

【讨论】:

    【解决方案2】:

    有几种方法可以解决这个问题,但首先,您应该简化访问时间戳的方式。

    当您使用 Airflow 时,其中 execution_date 是一个 pendulum.Pendulum 对象,您可以访问 execution_date.int_timestamp 属性。

    在更一般的情况下,假设您使用的是 Python 3.3+,有一种更简单的方法可以使用 datetime 对象上的 timestamp() 方法(也可以在 Pendulum 对象上使用)来获取纪元时间戳。

    execution_date.int_timestamp
    Output => 1555477775
    
    Python 3.3+:
    int(execution_date.timestamp())
    Output => 1555477775
    
    Python 2.7+:
    int(v.strftime('%s'))
    Output => 1555477775
    

    1。在模板内直接格式化

    此方法使用 datetime 对象的 timestamp() 方法生成一个浮点数,然后通过 Jinja2 模板的内置 int filter 运行。

    For Pendulum:
    {{ execution_date.int_timestamp }}
    
    For general datetime objects:
    {{ execution_date.timestamp()|int }}
    

    2。创建自定义 Jinja2 过滤器

    如果您在整个模板中的多个位置使用此转换,则可能值得创建一个过滤器来集中它。使用 Airflow,您可以在 DAG 对象上register a custom filter

    import time
    
    def epoch_int(v):
        return int(v.strftime('%s'))
    
    dag = DAG(
      ...
      user_defined_filters={
        "epoch_int": epoch_int,
      }
      ...
    )
    

    然后在你的模板中使用它。

    {{ execution_date|epoch_int }}
    

    【讨论】:

    • 第一个我不能做,因为我正在运行没有 Pendulum 的 Airflow 1.9。第二次我得到:AttributeError:'datetime.datetime'对象没有属性'timestamp'
    • 针对 python 2.7 兼容性编辑了解决方案 2
    • 你的 python 2 答案比它需要的要复杂得多 int(time.strftime("%s"))
    • 根据 Ash 的建议编辑了 python 2.7 解决方案 - 谢谢
    猜你喜欢
    • 2011-03-24
    • 2018-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-15
    相关资源
    最近更新 更多