Created
June 23, 2023 00:35
-
-
Save jongbinjung/b0e5cc070b91d94819d4e04842c50c38 to your computer and use it in GitHub Desktop.
Example of some common pendulum use cases
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
""" | |
Example of common pendulum use cases | |
Author: jongbin.jung | |
""" | |
import pandas as pd | |
import pendulum | |
current_time = pendulum.now() | |
print(current_time) | |
# > 2023-06-22T14:55:15.468166-07:00 | |
print(current_time.in_tz("US/Eastern")) | |
# > 2023-06-22T17:55:15.468166-04:00 | |
current_time.to_date_string() | |
# > '2023-06-22' | |
other_time = pendulum.parse("2023-03-06 15:32:00-07:00") | |
print(other_time) | |
# > 2023-03-06T15:32:00-07:00 | |
current_time.start_of("month") | |
# > DateTime(2023, 6, 1, 0, 0, 0, tzinfo=Timezone('America/Los_Angeles')) | |
current_time.start_of("week") # Returne most-recent Monday | |
# > DateTime(2023, 6, 19, 0, 0, 0, tzinfo=Timezone('America/Los_Angeles')) | |
current_time.subtract(weeks=1).start_of("week") # Monday of previous week | |
# > DateTime(2023, 6, 12, 0, 0, 0, tzinfo=Timezone('America/Los_Angeles')) | |
# Monday prior to a year from current time? | |
current_time.add(years=1).start_of("week") | |
# > DateTime(2024, 6, 17, 0, 0, 0, tzinfo=Timezone('America/Los_Angeles')) | |
# Wednesday after to a month from current time? | |
current_time.add(months=1).next(pendulum.WEDNESDAY) | |
# > DateTime(2023, 7, 26, 0, 0, 0, tzinfo=Timezone('America/Los_Angeles')) | |
# 12 hours later? | |
current_time.add(hours=12) | |
current_time + pendulum.duration(hours=12) | |
# With pandas DataFrames/Series ------------------------------------------------ | |
df = pd.DataFrame({"ts": pd.date_range("2023-06-04", "2023-06-05", periods=3)}) | |
# ts | |
# 0 2023-06-04 00:00:00 | |
# 1 2023-06-04 12:00:00 | |
# 2 2023-06-05 00:00:00 | |
df.assign( | |
this_week_of=df.ts.apply(lambda t: pendulum.instance(t).start_of("week")), | |
) | |
# ts this_week_of | |
# 0 2023-06-04 00:00:00 2023-05-29 00:00:00+00:00 2023-05-22 | |
# 1 2023-06-04 12:00:00 2023-05-29 00:00:00+00:00 2023-05-22 | |
# 2 2023-06-05 00:00:00 2023-06-05 00:00:00+00:00 2023-05-29 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment