简体   繁体   English

日期格式转换为文本(yyyymmdd)

[英]Date format conversion to text (yyyymmdd)

I have a date in format of YYYY-MM-DD (2022-11-01).我的日期格式为 YYYY-MM-DD (2022-11-01)。 I want to convert it to 'YYYYMMDD' format (without hyphen).我想将其转换为“YYYYMMDD”格式(不带连字符)。 Pls support.请支持。

I tried this...我试过这个...

df['ConvertedDate']= df['DateOfBirth'].dt.strftime('%m/%d/%Y')... but no luck df['ConvertedDate']= df['DateOfBirth'].dt.strftime('%m/%d/%Y')... 但运气不好

If I understand correctly, the format mask you should be using with strftime is %Y%m%d :如果我理解正确,你应该使用strftime的格式掩码是%Y%m%d

df["ConvertedDate"] = df["DateOfBirth"].dt.strftime('%Y%m%d')

Pandas itself providing the ability to convert strings to datetime in Pandas dataFrame with desire format. Pandas 本身提供了将 Pandas dataFrame 中的字符串转换为所需格式的日期时间的能力。

df['ConvertedDate'] = pd.to_datetime(df['DateOfBirth'], format='%Y-%m-%d').dt.strftime('%Y%m%d')

Referenced Example:参考示例:

import pandas as pd

values = {'DateOfBirth': ['2021-01-14', '2022-11-01', '2022-11-01']}

df = pd.DataFrame(values)
df['ConvertedDate'] = pd.to_datetime(df['DateOfBirth'], format='%Y-%m-%d').dt.strftime('%Y%m%d')

print (df)

Output: Output:

  DateOfBirth ConvertedDate
0  2021-01-14      20210114
1  2022-11-01      20221101
2  2022-11-01      20221101

This works这有效

from datetime import datetime 

initial = "2022-11-01"
time = datetime.strptime(initial, "%Y-%m-%d")
print(time.strftime("%Y%m%d"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM