Mark Smith
Mark Smith

Reputation: 767

Python 3.6 - Assign a 'YYYY-MM-DD' string to a variable as a datetime datatype?

I am processing messages received from RabbitMQ using a Python 3.6 script.

I am splitting each message string using commas that separate each part of its content. I then assign these as values to variables while setting their datatype...

I receive ints, decimals and strings within each message and can set these as needed however in two of the fields of the message I receive a 'YYYY-MM-DD' and a 'HH:mm:SS' string separated by commas.

Ideally I would like to assign these to variables as datetime objects so that I can use them in calculations later in my script...

I don't seem to be able to do this and I am thinking that this may not be the Pythonic way to do things - as when I have previously worked with datetime values that have been received as strings, I have had to convert them within a function that performs whatever calculation that is needed...

Essentially I have never converted (from a string) and stored a datetime datatype as a variable in Python nor have I seen this done else where...

Am I right in thinking that this is not possible or that it is not good practice and that date or time values should be stored as strings (or ints) until they are needed and then any conversions should be done within the function thats processing/or calculating using these values?

Conceptually I would like to be able to do something like:

todays_date = '2018-06-11' # assign a date string to a variable

todays_date = date(todays_date) # convert the date string to a date datatype

then later use the value of todays_date in a simple validation like the below...

if todays_date == date.today():

    do something...

or similar with time, e.g.

stored_time = '18:03:23' # assign time to a variable as a string

stored_time = time(stored_time) # convert the string to a time datatype

if stored_time - now() > (03:00:00):

    do something...

I haven't seen anything like this whilst searching, so I don't think it's possible even though logically you would think it should be but I wanted to check just in case I am miss-understanding something...

Any help will be much appreciated!

EDIT: Thanks to the answer below from Mulli - I was able to assign the strings as datetime variable values using the below:

msg[3] = datetime.strptime(msg[3],"%Y-%m-%d")  #  YYYY-MM-DD
msg[4] = datetime.strptime(msg[4], "%H:%M:%S.%f")  # HH:MM:SS.sss

Upvotes: 1

Views: 4275

Answers (1)

Mulli
Mulli

Reputation: 139

I think what you might be looking for is the datetime.strptime() method.

Here's the reference.

https://docs.python.org/3.6/library/datetime.html#datetime.datetime.strptime

Upvotes: 1

Related Questions