英文:
Snowpark python date format
问题
在Snowpark中,我有一个日期列的格式为%Y-%m-%d
。我想创建另一个列(它的一个版本),格式为%Y-%m
。在Pandas中,可以使用以下代码实现:
df.withColumn("start_month", date_format(col("start_date"), "yyyy-MM"))
英文:
In Snowpark, I have a date column in the format of %Y-%m-%d
. I want to create another column (a version of it) in the form of %Y-%m
. In Pandas this would have been:
df['start_month'] = pd.to_datetime(df['start_date']).dt.to_period('M')
How to do this in Snowpark?
答案1
得分: 0
使用
try_to_date
- 输入/列转换为日期数据类型(如果已经是日期,则可以跳过)to_varchar
- 转换为 YYYY-MM 字符串格式
代码:
import snowflake.snowpark as snowpark
from snowflake.snowpark.functions import col, sql_expr
def main(session: snowpark.Session):
df = session.create_dataframe(["2023-04-05", "2023-05-02"], schema=["start_date"])
df = df.select(col("start_date"), \
sql_expr("to_varchar(try_to_date(start_date, 'YYYY-MM-DD'), 'YYYY-MM')") \
.as_("start_month"))
return df
输出:
START_DATE | START_MONTH |
---|---|
2023-04-05 | 2023-04 |
2023-05-02 | 2023-05 |
import snowflake.snowpark as snowpark
import datetime
from snowflake.snowpark.functions import col, sql_expr
def main(session: snowpark.Session):
df = session.create_dataframe([datetime.date(2023,4,5), datetime.date(2023,5,2)], schema=["start_date"])
df = df.select(col("start_date"), \
sql_expr("to_varchar(start_date, 'YYYY-MM')").as_("start_month"))
return df
英文:
Using
try_to_date
- input/column to date data type(if already date it could be skippedto_varchar
- to YYYY-MM string format
Code:
import snowflake.snowpark as snowpark
from snowflake.snowpark.functions import col, sql_expr
def main(session: snowpark.Session):
df = session.create_dataframe(["2023-04-05", "2023-05-02"], schema=["start_date"])
df = df.select(col("start_date"), \
sql_expr("to_varchar(try_to_date(start_date, 'YYYY-MM-DD'), 'YYYY-MM')") \
.as_("start_month"))
return df
Output:
START_DATE | START_MONTH |
---|---|
2023-04-05 | 2023-04 |
2023-05-02 | 2023-05 |
import snowflake.snowpark as snowpark
import datetime
from snowflake.snowpark.functions import col, sql_expr
def main(session: snowpark.Session):
df = session.create_dataframe([datetime.date(2023,4,5), datetime.date(2023,5,2)], schema=["start_date"])
df = df.select(col("start_date"), \
sql_expr("to_varchar(start_date, 'YYYY-MM')").as_("start_month"))
return df
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论