Python: convert datetime format - python

I've a string in the following date/time format:
2018-05-20T07:06:23.226
I need to convert it to the following format:
2018-05-20 06:23 AM
I tried the following code, but I'm surely making some mistake here:
date = "2018-05-20T07:06:23.226"
d = datetime.datetime.strptime('date', '%Y-%m-%dT%H:%M:%S.%f')
new_date = d.strftime('%y-%m-%d %H:%M %p')
I always get the following error:
ValueError: time data 'date' does not match format '%Y-%m-%dT%H:%M:%S.%f'

replace:
d = datetime.datetime.strptime('date', '%Y-%m-%dT%H:%M:%S.%f')
with
d = datetime.datetime.strptime(date, '%Y-%m-%dT%H:%M:%S.%f')
Also
new_date = d.strftime('%y-%m-%d %H:%M %p')
with
new_date = d.strftime('%Y-%m-%d %I:%M %p')

If you wish to use variable inside string, you can do it since Python 3.6:
date = "2018-05-20T07:06:23.226"
d = datetime.datetime.strptime(f'{date}', '%Y-%m-%dT%H:%M:%S.%f')
new_date = d.strftime('%y-%m-%d %H:%M %p')

Related

In Python, how will we convert this type of string into datetime format in pandas dataframe?

I have done:
1.
from datetime import datetime
date_string = df['Date']
format = '%m/%d/%Y %I:%M %p'
for i in date_string:
my_date = datetime.strptime(i, format)
print (my_date.strftime(format))
df['Date']=pd.to_datetime(df['Date'],format='%m/%d/%Y, %I:%M %p')
Use %y for years in format YY, %Y is for format YYYY:
df['Date']=pd.to_datetime(df['Date'],format='%m/%d/%y, %I:%M %p')
print (df)
Date
0 2018-02-26 12:31:00

How to format string time object with python?

I am using django python. Now I want to convert the following timing string into hours, minutes ,am/pm format.
string_time = '2022-09-13 11:00:00.996795+00'
expected output:
11:00 am
actual output is :
ValueError: time data '2022-09-13 11:00:00.996795+00' does not match format '%m/%d/%y %H:%M:%S'
my code :
def time_slots(self,string_time='2022-09-13 11:00:00.996795+00'):
print(datetime.strptime(string_time, '%m/%d/%y %H:%M:%S'),type(start_time))
start_time = datetime.strptime(string_time, '%m/%d/%y %H:%M:%S')
return formated_start_time
When you remove the last three chars ('+00') and replace the space with T you can use datetime.datetime.fromisoformat(str) to get a datetime object.
from datetime import datetime
timestr = '2022-09-13 11:00:00.996795+00'
timestr = timestr.rstrip(timestr[-3:]).replace(' ', 'T')
date = datetime.fromisoformat(timestr)
from there you can use date.hour and date.minute to get the values you want.
e.g.:
hour = date.hour%12
minute = date.minute
addition = ''
if date.hour > 12:
addition = 'pm'
else:
addition = 'am'
print(f'{hour}:{minute} {addition}')
I'm not sure if the last string +00 is useful.
If not, the following implementation can help you.
from datetime import datetime
def time_slots(string_time='2022-09-13 11:00:00.996795+00'):
date = datetime.strptime(string_time[:-3], '%Y-%m-%d %H:%M:%S.%f')
return date.strftime("%H:%M %p")
output = time_slots()
print(output) # the output is: 11:00 AM
You can use the parse function provided by dateutil:
from dateutil import parse
string_time = '2022-09-13 11:00:00.996795+00'
dt = parse(string_time)
return dt.strftime("%H:%M %p")
Result: 11:00 AM

issue in conversion of date using python

I am very new in python working on dates. I have 2 type of dates (because getting in array dynamically). Something like this ['2022-02-17 08:29:36.345374' , '2021-03-18 08:29:36']
I am trying to get these in this format 17/02/2022 08:29 PM.
Until now trying something like this:
def update_date(datetime):
date_formating = datetime.strptime(date_time, '%m/%d/%Y %I:%M %p')
return date_formating
but getting errors like:
ValueError: time data '2022-02-17 08:29:36.345374' does not match format '%m/%d/%Y %I:%M %p'
I need a solution which can turn both formats I am getting into desired format. Any help would be highly appreciated.
Try a list comprehension with datetime.fromisoformat(date_string):
>>> from datetime import datetime
>>> date_strs = ['2022-02-17 08:29:36.345374', '2021-03-18 08:29:36']
>>> [datetime.fromisoformat(s).strftime('%d/%m/%Y %I:%M %p') for s in date_strs]
['17/02/2022 08:29 AM', '18/03/2021 08:29 AM']
The times in the given list come in two different formats
with microseconds
with seconds (and no microseconds)
This code highlights the differences and would work:
import datetime as dt
t = ['2022-02-17 08:29:36.345374' , '2021-03-18 08:29:36']
# format with microseconds
d1 = dt.datetime.strptime(t[0], '%Y-%m-%d %H:%M:%S.%f')
# format with seconds
d2 = dt.datetime.strptime(t[1], '%Y-%m-%d %H:%M:%S')
# format user wants
x = d1.strftime('%m/%d/%Y %I:%M %p')
y = d2.strftime('%m/%d/%Y %I:%M %p')
print(x)
print(y)
The result:
02/17/2022 08:29 AM
03/18/2021 08:29 AM

Convert String to Python datetime Object without Zero Padding

I'm using python 3.5.
I have a string formatted as mm/dd/yyyy H:MM:SS AM/PM that I would like as a python datetime object.
Here is what I've tried.
date = "09/10/2015 6:17:09 PM"
date_obj = datetime.datetime.strptime(date, '%d/%m/%Y %I:%M:%S %p')
But this gets an error because the hour is not zero padded. The formatting was done per the table on the
datetime documentation, which does not allow the hour to have one digit.
I've tried splitting the date up, adding a zero and then reassembling the string back together, while this works, this seems less robust/ideal.
date = "09/10/2015 6:17:09 PM"
date = date.split()
date = date[0] + " 0" + date[1] + " " + date[2]
Any recommendation on how to get the datetime object directly, or a better method for padding the hour would be helpful.
Thank you.
There is nothing wrong with this code:
>>> date = "09/10/2015 6:17:09 PM"
>>> date_obj = datetime.datetime.strptime(date, '%m/%d/%Y %I:%M:%S %p')
>>> date_obj
datetime.datetime(2015, 9, 10, 18, 17, 9)
>>> print(date_obj)
2015-09-10 18:17:09
The individual attributes of the datetime object are integers, not strings, and the internal representation uses 24hr values for the hour.
Note that I have swapped the day and month in the format strings as you state that the input format is mm/dd/yyyy.
But it seems that you actually want it as a string with zero padded hour, so you can use datetime.strftime() like this:
>>> date_str = date_obj.strftime('%m/%d/%Y %I:%M:%S %p')
>>> print(date_str)
09/10/2015 06:17:09 PM
# or, if you actually want the output format as %d/%m/%Y....
>>> print(date_obj.strftime('%d/%m/%Y %I:%M:%S %p'))
10/09/2015 06:17:09 PM

python strptime wrong format with 12-hour hour

My string format currently is datetime.strptime(date_as_string, '%d/%m/%y %I:%M %p')
this unfortunately does not work with input such as 1/12/07 00:07 AM
How I can get strptime to recogize this format ?
EDIT:
ValueError: time data '1/12/07 00:07 AM' does not match format '%d/%m/%y %I:%M %p'
'00' is not a valid 12-hour hour, but if your input date string is inconsistently formatted you might be able to get away with something like this:
>>> from datetime import datetime as dt
>>> date_as_string = '1/12/07 00:07 AM'
>>> format_12 = '%d/%m/%y %I:%M %p'
>>> format_24 = '%d/%m/%y %H:%M %p'
>>> date_string, time_string = date_as_string.split(' ', 1)
>>> try:
... dt.strptime(date_string + ' ' + time_string, format_12)
... except ValueError:
... dt.strptime(date_string + ' ' + time_string, format_24)
...
datetime.datetime(2007, 12, 1, 0, 7)
'1/12/07 00:07 AM' has incorrect format because in the 12-hour format the hour can be in range 1-12 and not 0.

Categories

Resources