Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
712 views
in Technique[技术] by (71.8m points)

Insert a value in date format dd-mm-yyyy in dictionary in python

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Do your dates always look the same? If not:

Installation

pip3 install python-dateutil
pip3 install pytz

Code

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.')

Tested with Python 3.4.3 on Ubuntu 14.04.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...