Snowpark Python日期格式

huangapple go评论65阅读模式
英文:

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 skipped
  • to_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

huangapple
  • 本文由 发表于 2023年4月17日 13:28:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76031957.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定