如何将整数转换为日期对象python? [英] How to convert integer into date object python?

查看:2853
本文介绍了如何将整数转换为日期对象python?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python中创建一个模块,其中我收到整数格式的日期,如 20120213 ,这意味着2012年2月13日。现在,我想将这个整数格式化的日期转换成一个python日期对象。



另外,如果有任何方法可以减去/添加这种整数格式化日期的天数以相同的格式接收日期值?喜欢从 20120213 中减去30天,并收到 20120114

解决方案


我会建议以下简单的转换方法:

  from datetime import datetime,timedelta 
s =20120213
#你也可以导入日期而不是datetime并使用它。
date = datetime(year = int(s [0:4]),month = int(s [4:6]),day = int(s [6:8]))

为了添加/减去任意数量的天数(秒工作太多),您可以执行以下操作:

  date + = timedelta(days = 10)
date - = timedelta(days = 5)

并使用以下方式转换:

  s = date.strftime(%Y%m%d)

要将整数转换成字符串,请使用:

  s ={0:-08d}格式(i)

八个贞节长,左半数为零,即使年份小于1000(负年也可能变得有趣)。



进一步参考: datetime对象 timedelta对象


I am creating a module in python, in which I am receiving the date in integer format like 20120213, which signifies the 13th of Feb, 2012. Now, I want to convert this integer formatted date into a python date object.

Also, if there is any means by which I can subtract/add the number of days in such integer formatted date to receive the date value in same format? like subtracting 30 days from 20120213 and receive answer as 20120114?

解决方案

I would suggest the following simple approach for conversion:

from datetime import datetime, timedelta
s = "20120213"
# you could also import date instead of datetime and use that.
date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))

For adding/subtracting an arbitary amount of days (seconds work too btw.), you could do the following:

date += timedelta(days=10)
date -= timedelta(days=5)

And convert back using:

s = date.strftime("%Y%m%d")

To convert the integer to a string safely, use:

s = "{0:-08d}".format(i)

This ensures that your string is eight charecters long and left-padded with zeroes, even if the year is smaller than 1000 (negative years could become funny though).

Further reference: datetime objects, timedelta objects

这篇关于如何将整数转换为日期对象python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆