在python的字典中插入日期格式为dd-mm-yyyy的值 [英] Insert a value in date format dd-mm-yyyy in dictionary in python

查看:550
本文介绍了在python的字典中插入日期格式为dd-mm-yyyy的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建具有某些值的字典,其中包括一个人的出生日期.但是,当我运行我的代码时,它给出了一个错误"datetime.datetime没有属性datetime".这是我的代码:

I am creating a dictionary having some values including a date of birth of a person. But when I run my code, it is giving an error "datetime.datetime has no attribute datetime" . Here is my code:

    import re
from datetime import date
import datetime
from datetime import datetime
userDetails=[]
dateOfBith='9-9-1992'
#datetimeparse = datetime.strptime(dateOfBith,'%dd-%mm-%yyyy')
datetimeparse = datetime.datetime.strptime(dateOfBith, '%Y-%m-%d').strftime('%d/%m/%y')
dateparse = datetime(datetimeparse)
accountDetails= {"FirstName": "ajay", "LastName": "kumar","Account Number":"4242342345234","Balance Currency":"Rs","Balance Amount":"5000"}
accountDetails["DateOfBirth"] = dateparse

推荐答案

您的日期看起来总是一样吗?如果没有:

Do your dates always look the same? If not:

pip3 install python-dateutil
pip3 install pytz

代码

import datetime
import dateutil
import dateutil.parser
import pytz

date_in = dateOfBith = '9-9-1992'

try:
    if date_in.count('.') >= 2:
        date_out = dateutil.parser.parse(date_in, dayfirst=True)
    else:
        date_out = dateutil.parser.parse(date_in, dayfirst=False)
        # Additional parameters for parse:
        # dayfirst=True  # In ambiguous dates it is assumed that the day is further forward.
        # default=datetime.datetime(1,1,1,0,0,0)  # Used only piecewise, i.e. if the year is missing, year will be 1, the rest remains!
        # fuzzy=True  # Ignores words before and after the date.
except ValueError as e:
    print(repr(e))

print(date_out.isoformat())  # returns 1992-09-09T00:00:00

timezone_utc = pytz.utc
timezone_berlin = pytz.timezone('Europe/Berlin')  # Put your capital here!

try:
    date_out = timezone_berlin.localize(date_out)
except ValueError as e:
    print(repr(e))

print(date_out.isoformat())  # returns 1992-09-09T00:00:00+02:00

if date_out > timezone_utc.localize(datetime.datetime.utcnow()):
    print('The date is in the future.')

在Ubuntu 14.04上使用Python 3.4.3进行了测试.

Tested with Python 3.4.3 on Ubuntu 14.04.

这篇关于在python的字典中插入日期格式为dd-mm-yyyy的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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