How to convert a string to datetime object [duplicate] - python

This question already has answers here:
How do I parse an ISO 8601-formatted date?
(29 answers)
Closed 5 years ago.
With the time value being:
value = '2017-08-31T02:24:29.000Z'
I try to convert it to a datetime object with:
import datetime
datetime_object = datetime.datetime.strptime(value, '%Y-%b-%d %I:%M%p')
But the command crashes with the exception:
ValueError: time data '2017-08-31T02:24:29.000Z' does not match format '%Y-%b-%d %I:%M%p'

You should be using a builtin Python's datautil module instead of date time:
import dateutil.parser
value = '2017-08-31T02:24:29.000Z'
result = dateutil.parser.parse(value)

First of all, you are missing the formatter for the microsecond.
Second of all, there is no second colon for dividing the minute and second.
Third, the %b operator is for the monthname (Jan,Feb,etc.). You want to use %m.
Final format is '%Y-%m-%dT%I:%M:%S.%fZ'.
This is your code:
datetime_object = datetime.datetime.strptime(value, '%Y-%m-%dT%I:%M:%S.%fZ')
You should get 2017-08-31 02:24:29 as the value of datetime_object.

Related

How do I get rid of the year, month, and day? [duplicate]

This question already has answers here:
Compare only time part in datetime - Python
(3 answers)
Closed 1 year ago.
I was trying to write a program that converts a string to datetime type. The code looks like this.
import datetime
time="20:36"
p=datetime.datetime.strptime(time, "%H:%M")
print(p)
and the output was
1900-01-01 20:36:00
How do I get rid of the '1990-01-01' ?
It's unfortunate that you cannot simply write
p = datetime.time.strptime(time, "%H:%M")
because time.strptime is not defined. You are forced to use datetime.strptime, which returns a datetime object no matter what fields are actually being parsed.
On the plus side, you can get the time object you want relatively easily.
t = p.time()
print(t) # Outputs 20:36:00
You're creating a datetime object from your string and displaying the datetime as a whole.
What you should do:
display just the time part:
use strftime:
The code
import datetime
time="20:36"
p=datetime.datetime.strptime(time, "%H:%M")
print(p.strftime("%H:%M"))
use time:
The code:
import datetime
time="20:36"
p=datetime.datetime.strptime(time, "%H:%M")
print(p.time())
What you really should do:
Create a time object from your data. For that you can use datetime.time
import datetime
time="20:36"
hour, minute = time.split(":")
t = datetime.time(hour=int(hour), minute=int(minute))
print(t)

Convert date string format to a datetime Python Object [duplicate]

This question already has answers here:
Convert string "Jun 1 2005 1:33PM" into datetime
(26 answers)
Closed 2 years ago.
i've one doubt.
I'm doing request to an API which return me event date. I was hope that date will be a timestamp, but i get this value:
{"date":"2020-08-24T21:15:00+00:00"}
I want to get a python datetime object.
How can I do that?
from datetime import datetime
dates = {"date":"2020-08-24T21:15:00+00:00"}
date = dates.get("date")
day = datetime.strptime(date, "%Y-%m-%dT%H:%M:%S+00:00")
Your looking for strptime.
Heres a good article:
https://www.programiz.com/python-programming/datetime/strptime
Use dateutil.parser which smartly parse date string:
import json
import dateutil.parser
result = '{"date":"2020-08-24T21:15:00+00:00"}'
x = json.loads(result)
dt = dateutil.parser.parse(x['date'])
# 2020-08-24 21:15:00+00:00
print(dt)
# <class 'datetime.datetime'>
print(type(dt))
I think you can do it respecting the format while parsing the string:
You have to try to follow the structure of the string and assign each value to the correct time value. For example:
str = '2018-06-29 08:15:27.243860'
time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')
Note that your case is pretty different.
It could be similar to '%Y-%m-%dT%H:%M:%S.f'

How to convert date as string to date type [duplicate]

This question already has answers here:
Convert string "Jun 1 2005 1:33PM" into datetime
(26 answers)
Closed 3 years ago.
I have a variable '2019-05-30 21:01:09' that needs to be converted into 2019-05-30 21:01:09. What is the best way to go about this.
from datetime import datetime
strToDate = datetime.strptime('2019-05-30 21:01:09','%Y-%m-%d %H:%M:%S')
strptime() allows for the conversion of string to date time object provided that you give the format the function should expect as the second argument
You can using datetime library
from datetime import datetime
datetime.strptime('2019-05-30 21:01:09', '%Y-%m-%d %H:%M:%S')
https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

Converting month in number to word [duplicate]

This question already has answers here:
Parse date string and change format
(10 answers)
Closed 4 years ago.
i have string
date = "2018-09-12"
i want to get output like 2018-September-12
and i try like this
from datetime import datetime
date3 = datetime.strptime(date, '%Y-%m%B-%d')
or date3 = datetime.strptime(date, '%Y-%B-%d')
but always get time data '2018-09-12' does not match format '%Y-%m%B-%d'
Use strftime
Ex:
from datetime import datetime
date = "2018-09-12"
date3 = datetime.strptime(date, '%Y-%m-%d').strftime("%Y-%B-%d")
print(date3)
Output:
2018-September-12
strptime to convert string datetime to datetime object.
strftime to convert datetime object to required string format.

Converting UTC-Date-String to Unixtimestamp [duplicate]

This question already has answers here:
Parsing datetime strings containing nanoseconds
(5 answers)
Closed 4 years ago.
I have a date formated like this: "2018-06-12T13:58:36.663550655Z"
I want be convert this string into a Unix time stamp.
This is my code:
from datetime import datetime
date = '2018-06-12T14:03:35.306662173Z'
time = datetime.strptime(date,"%Y-%m-%dT%H:%M:%S.%fZ")
unixTime = datetime.utcfromtimestamp(time)
When i run it, there's a error:
ValueError: time data '2018-06-12T14:03:35.306662173Z' does not match
format '%Y-%m-%dT%H:%M:%S.%fZ'
Would be nice if someone could help me !
Thanks!
Try stripping the extra info.
Ex:
import time
from datetime import datetime
date = '2018-06-12T14:03:35.306662173Z'
d = datetime.strptime(date[:26],"%Y-%m-%dT%H:%M:%S.%f")
unixTime = time.mktime(d.timetuple())
print(unixTime)
Output:
1528792415.0

Categories