简体   繁体   English

如何将 python 中的年月日转换为年?

[英]How to convert year-month-day to just years in python?

So I have this column in a dataframe that has 4896 rows of datatimes in this shape:所以我在 dataframe 中有这个列,它有 4896 行这种形状的数据时间:

    2018-10-24
    2014-04-10
    2008-05-21
    ...

And I would like to transform or convert this data to years only (like 2018.15) -> convert the day and month to year time and have only the years!我只想将这些数据转换或转换为年(如 2018.15)-> 将日和月转换为年时间并且只有年!

How can I do so??我怎么能这样做? Thank you so much!!太感谢了!!

In: 2018-10-24
Out: 2018.56 (for example)

Using just base Python (as you didn't specify that you have a pandas dataframe - pandas has specific functions to perform calculations with datetime objects):仅使用基数 Python(因为您没有指定您有一个 pandas dataframe - pandas 具有使用日期时间对象执行计算的特定函数):

from datetime import datetime
    
#takes as arguments the date as a string and an optional format string
def floatyear(str, fmtstr="%Y-%m-%d"):
    t = datetime.strptime(str, fmtstr)
    t_first = datetime(t.year, 1, 1, 0, 0, 0)
    t_last = datetime(t.year, 12, 31, 0, 0, 0)
    return t.year + ((t-t_first).days/(t_last-t_first).days)

print(floatyear("2018-10-24", "%Y-%m-%d"))

Sample output:样本 output:

2018.8131868131868

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

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