Date time format conversion in python [duplicate] - python

This question already has answers here:
Convert 12-hour date/time to 24-hour date/time
(8 answers)
Convert string "Jun 1 2005 1:33PM" into datetime
(26 answers)
Closed 7 years ago.
I have a string containing time stamp in format
(DD/MM/YYYY HH:MM:SS AM/PM), e.g."12/20/2014 15:25:05 pm"
.
The time here is in 24 Hrs format.
I need to convert into same format but with time in 12-Hrs format.
I am using python version 2.6.
I have gone through time library of python but couldn't come up with any solution.

View Live ideOne use Python datetime,
>>> from datetime import datetime as dt
>>> date_str='12/20/2014 15:25:05 pm'
>>> date_obj = dt.strptime(date_str, '%m/%d/%Y %H:%M:%S %p')
>>> dt.strftime(date_obj, '%m/%d/%Y %I:%M:%S %p')
'12/20/2014 03:25:05 PM'

The trick is to convert your Input date string to Python datetime object and then convert it back to date string
import datetime
#Input Date String
t = "12/20/2014 15:25:05 pm"
#Return a datetime corresponding to date string
dateTimeObject = datetime.datetime.strptime(t, '%m/%d/%Y %H:%M:%S %p')
print dateTimeObject
Output: 2014-12-20 15:25:05
#Return a string representing the date
dateTimeString = datetime.datetime.strftime(dateTimeObject, '%m/%d/%Y %I:%M:%S %p')
print dateTimeString
Output: 12/20/2014 03:25:05 PM

After creating a datetime object using strptime you then call strftime and pass the desired format as a string see the docs:
In [162]:
t = "12/20/2014 15:25:05 pm"
dt.datetime.strftime(dt.datetime.strptime(t, '%m/%d/%Y %H:%M:%S %p'), '%m/%d/%Y %I:%M:%S %p')
Out[162]:
'12/20/2014 03:25:05 PM'

Shortest & simplest solution --
I really appreciate & admire (coz I barely manage to read man pages :P) you going through time documentation, but why use "astonishing" & "cryptic" code when simple code could get the job done
Just extract the hour part as int & replace it by hrs-12 if it is greater than 12
t = "12/20/2014 15:25:05 pm"
hrs = int( t.split()[1][:2] )
if hrs > 12:
t = t.replace( str(hrs), str(hrs-12) )
Output
See explaination & live output here
Using Lambda
If you like one liners, checkout f() below
t = "12/20/2014 15:25:05 pm"
f = lambda tym: tym.replace(str(int(tym.split()[1][:2])), str(int(tym.split()[1][:2])-12)) if int(tym.split()[1][:2]) > 12 else tym
print(f(t))

Related

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

Python strptime not parsing time zone EST %z

I am trying to parse the string '10/23/2019 6:02:05 PM EST' into a datetime with time zone using Python 3.7.
Code:
from datetime import datetime
timestamp = datetime.strptime(date_str, '%m/%d/%Y %I:%M:%S %p %Z')
Error:
ValueError: time data '10/23/2019 6:02:05 PM EST' does not match format '%m/%d/%Y %I:%M:%S %p %Z'
When I create a datetime and output it using the same formatting I get the correct output. The only difference is that there is a 0 in front of the hour, but adding 0 in front of the 6 in my date string results in the same error.
My current solution is to parse the datetime without the timezone and then localize it, but this is not ideal.
date_lst = date.split()
date_str = ' '.join(date_lst[0:3])
timestamp = datetime.strptime(date_str, '%m/%d/%Y %I:%M:%S %p')
new_tz = pytz.timezone(date_lst[3])
timestamp_tz = new_tz.localize(timestamp)```
It is reasonable to expect that parsing a string with a timezone included would produce a timezone aware datetime object.
Try it
>>timestamp = datetime.strptime('10/23/2019 6:02:05 PM EST', '%m/%d/%Y %I:%M:%S %p EST')
>>2019-10-23 06:02:05
You can try this.

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

Change Date Format In Python [duplicate]

This question already has answers here:
Convert string "Jun 1 2005 1:33PM" into datetime
(26 answers)
Closed 8 years ago.
I need to convert date string "Dec 17 00:00:06" to string "2014-12-17 00:00:06" in python. I looked at the datetime.strptime but still can't find a way for this.
eg:
Dec 17 00:00:06 to 2014-12-17 00:00:06
You can use datetime module.
For e.g.
>>> import datetime
>>> do = datetime.datetime.strptime("Dec 17 2014 00:00:06", "%b %d %Y %H:%M:%S")
>>> do.strftime("%Y-%m-%d %H:%M:%S")
'2014-12-17 00:00:06'
We can replace year value to 2014 like following:
>>> do = datetime.datetime.strptime("Dec 17 00:00:06", "%b %d %H:%M:%S")
>>> do.strftime("%Y-%m-%d %H:%M:%S")
'1900-12-17 00:00:06'
>>> do1 = do.replace(year=2014)
>>> do1.strftime("%Y-%m-%d %H:%M:%S")
'2014-12-17 00:00:06'
If we want only time value then we can try like-
>>> do = datetime.datetime.strptime("Dec 17 00:00:06", "%b %d %H:%M:%S")
>>> do.strftime("%H:%M:%S")
'00:00:06'
Updated: update datetime string from file with its time string.
Algo:
Get content from the input text file.
Used re module i.e regular expression to get all pattern from content.
Use set method to remove duplicate values.
Convert datetime string to time string and update content.
Write new content into same file or other file.
code is:-
import datetime
import re
p = "/home/vivek/Desktop/input.txt"
with open(p, "rb") as fp:
content = fp.read()
date_values = set(re.findall("\[([^]]+)\]", content))
for i in date_values:
do = datetime.datetime.strptime(i, "%b %d %H:%M:%S")
content = content.replace("[%s]"%i, "%s"%(do.strftime("%H:%M:%S")) )
p = "/home/vivek/Desktop/output.txt"
with open(p, "wb") as fp:
fp.write(content)
Using datetime module will help you out.
from datetime import datetime
Firstly convert your date string to a datetime object by writing the line below.
date_obj = datetime.strptime("Dec 17 2014 00:00:06", "%b %d %Y %H:%M:%S")
Then convert that date object to a string.
date_obj.strftime("%Y-%m-%d %H:%M:%S")
You can change the parameters of the above strftime() function, and get different formats as per your requirments. Please follow python datetime
Here is the link to the options for the parameters which can be passed in the strftime() function parameter options
Go and play around as per your requirement.
from dateutil import parser
parser.parse('Dec 17 00:00:06').isoformat()
>>> '2015-12-17T00:00:06'

Convert string datetime to timestamp and vice verse in python [duplicate]

This question already has answers here:
Convert string "Jun 1 2005 1:33PM" into datetime
(26 answers)
Closed 8 years ago.
I have a date stored as a string:-
16/07/2014 13:00:00
I want to convert this into timestamp.
Also from timestamp to this format again.
Please suggest the best possible way to do this in python.
You can use datetime to handle combined dates and times. You could parse this string using datetime.strptime but then you'd have to manually select the formatting.
Alternatively you can use the dateutil package which has a parser which can intelligently guess the string format and return a datetime object, as shown below:
from dateutil import parser
s = '16/07/2014 13:00:00'
d = parser.parse(s)
print(d)
# 2014-07-16 13:00:00
print(type(d))
# datetime.datetime
The documentation to look into this deeper is here
The functions you are looking for are time.strptime(string[, format]) to go from string to timestamp, and then from timestamp to string is time.strftime(format[, t])
Here is an example for your format:
>>> from datetime import datetime
>>>
>>> date_object = datetime.strptime('16/07/2014 13:00:00', '%d/%m/%Y %H:%M:%S')
>>> print date_object
2014-07-16 13:00:00
The to go back to your format (I have used gmtime() to get the current time to show you can convert any datetime to your desired format)
>>> from time import gmtime, strftime
>>> date_string = strftime("%d/%m/%Y %H:%M:%S", gmtime())
>>> print date_string
17/09/2014 09:31:00
Your best bet is the datetime library: https://docs.python.org/2/library/datetime.html
import datetime
mytime='16/07/2014 13:00:00'
pythontime=datetime.datetime.strptime(mytime, '%d/%m/%Y %H:%M:%S')
stringtime=pythontime.strftime('%d/%m/%Y %H:%M:%S')
Enjoy!

Categories

Resources