Python日期字符串到日期对象

本文翻译自:Python date string to date object

How do I convert a string to a date object in python? 如何在python中将字符串转换为日期对象?

The string would be: "24052010" (corresponding to the format: "%d%m%Y" ) 该字符串将是: "24052010" (对应格式: "%d%m%Y"

I don't want a datetime.datetime object, but rather a datetime.date. 我不想要datetime.datetime对象,而是datetime.date。


#1楼

参考:https://stackoom.com/question/BlPQ/Python日期字符串到日期对象


#2楼

import datetime
datetime.datetime.strptime('24052010', '%d%m%Y').date()

#3楼

You can use strptime in the datetime package of Python: 您可以在Python的datetime包中使用strptime

>>> import datetime
>>> datetime.datetime.strptime('24052010', "%d%m%Y").date()
datetime.date(2010, 5, 24)

#4楼

Directly related question: 直接相关的问题:

What if you have 怎么样?

datetime.datetime.strptime("2015-02-24T13:00:00-08:00", "%Y-%B-%dT%H:%M:%S-%H:%M").date()

and you get: 你得到:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/_strptime.py", line 308, in _strptime
    format_regex = _TimeRE_cache.compile(format)
  File "/usr/local/lib/python2.7/_strptime.py", line 265, in compile
    return re_compile(self.pattern(format), IGNORECASE)
  File "/usr/local/lib/python2.7/re.py", line 194, in compile
    return _compile(pattern, flags)
  File "/usr/local/lib/python2.7/re.py", line 251, in _compile
    raise error, v # invalid expression
sre_constants.error: redefinition of group name 'H' as group 7; was group 4

and you tried: 你尝试过:

<-24T13:00:00-08:00", "%Y-%B-%dT%HH:%MM:%SS-%HH:%MM").date()

but you still get the traceback above. 但你仍然得到上面的追溯。

Answer: 回答:

>>> from dateutil.parser import parse
>>> from datetime import datetime
>>> parse("2015-02-24T13:00:00-08:00")
datetime.datetime(2015, 2, 24, 13, 0, tzinfo=tzoffset(None, -28800))

#5楼

Use time module to convert data. 使用时间模块转换数据。

Code snippet: 代码段:

import time 
tring='20150103040500'
var = int(time.mktime(time.strptime(tring, '%Y%m%d%H%M%S')))
print var

#6楼

There is another library called arrow really great to make manipulation on python date. 还有另一个名为arrow库非常适合在python日期进行操作。

import arrow
import datetime

a = arrow.get('24052010', 'DMYYYY').date()
print(isinstance(a, datetime.date)) # True
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值