Dominik
07/04/2024, 3:01 PMMarvin
07/04/2024, 3:01 PMdatetime.datetime.now()
returning the deployment creation date in Prefect 2.
However, this behavior might be due to the flow being serialized and then deserialized in such a way that the timestamp is captured at the time of deployment, not at the time of execution. Here's a workaround using Prefect's built-in utilities to ensure you get the current date and time at the moment the flow runs:
You can use the pendulum
library, which is included with Prefect, to get the current datetime. Here’s how you can ensure you're getting the current datetime at the time the flow runs:
python
import pendulum
from prefect import flow, task
@task
def display_current_datetime():
current_datetime = pendulum.now()
print(f"The current datetime is: {current_datetime}")
@flow
def my_flow():
display_current_datetime()
if __name__ == "__main__":
my_flow()
Using pendulum.now()
ensures that the flow gets the current date and time at runtime, rather than at the time the deployment is created.
You can refer to the Prefect documentation on tasks and flows here for more information.