Convert String to Python datetime Object without Zero Padding - python

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

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

get hours from full date date to python3

I work with api in python3 in this api return date like this
'Jun 29, 2018 12:44:14 AM'
but i need just hours, minute ad second like this
12:44:14
are there a fonction that can format this
It looks like the output is a string. So, you can use string slicing:
x = 'Jun 29, 2018 12:44:18 AM'
time = x[-11:-3]
It's best to use negative indexing here because the day may be single-digit or double-digit, so a solution like time = x[13:21] won't work every time.
If you're inclined, you may wish to use strptime() and strftime() to take your string, convert it into a datetime object, and then convert that into a string in HH:MM:SS format. (You may wish to consult the datetime module documentation for this approach).
Use the datetime module. Use .strptime() to convert string to datetime object and then .strftime() to convert to your required string output. Your sample datetime string is represented as '%b %d, %Y %H:%M:%S %p'
Ex:
import datetime
s = 'Jun 29, 2018 12:44:14 AM'
print( datetime.datetime.strptime(s, '%b %d, %Y %H:%M:%S %p').strftime("%H:%M:%S") )
Output:
12:44:14

Parse and extract values from time format in python

I am trying to parse and extract values from my time data 2018-03-11 13:15:31.734874+01:00.
I'm using strptime() to do this with the %Y %m %d %H:%M:%S.%f %Z format but I am getting this error:
ValueError: time data '2018-03-11 13:15:31.734874+01:00' does not match format '%Y %m %d %H:%M:%S.%f %Z'
Also, I don't know how to handle the +1:00 in my time data. Can anyone help?
There are two problems here to solve.
First is the format string. It should be %Y-%m-%d %H:%M:%S.%f%z to match exact date separators and timezone sequence (without space).
From strftime and strptime Behavior:
%z (lower case) UTC offset in the form +HHMM or -HHMM (empty string if the object is naive). (empty), +0000, -0400, +1030
Second is the colon (:) in timezone offset '+01:00'. That can be left out using substring: s[:-3]+s[-2:] or string substitute.
So the final answer is as below.
from datetime import datetime
s = '2018-03-11 13:15:31.734874+01:00'
datetime.strptime(s[:-3]+s[-2:], '%Y-%m-%d %H:%M:%S.%f%z')
%Y %m %d  should be changed to %Y-%m-%d to match with the time string. Also, you need to remove the last : from the input to use with %z.
Here is how you should do:
import datetime
s = '2018-03-11 13:15:31.734874+01:00'
print(datetime.datetime.strptime(''.join(s.rsplit(':', 1)), '%Y-%m-%d %H:%M:%S.%f%z'))
# 2018-03-11 13:15:31.734874+01:00
At first:
%Y %m %d will not match 2018-03-11. You need to adapt it to the time string! %Y-%m-%d instead should work.
Secondly:
IF you are in python3, the %z was added for time stamps. However the timestamp has to be without the colon, e.g. +0100instead of +01:00. Therefore, if you use python3 this works:
>>> time_string = '2018-03-11 13:15:31.734874+01:00'
>>> time_string = ''.join(time_string.rsplit(':', 1))
>>> datetime.datetime.strptime(time_string, '%Y-%m-%d %H:%M:%S.%f%z')
datetime.datetime(2018, 3, 11, 13, 15, 31, 734874, tzinfo=datetime.timezone(datetime.timedelta(0, 3600)))
Btw the time_string after the editing looks like that:
>>> time_string
'2018-03-11 13:15:31.734874+0100'
IF you are in python2, the %z won't work, here you have to use the parse function of the dateutil module, which is straight forward.
>>> from dateutil.parser import parse
>>> parse('2018-03-11 13:15:31.734874+01:00')
datetime.datetime(2018, 3, 11, 13, 15, 31, 734874, tzinfo=tzoffset(None, 3600))

Date time format conversion in python [duplicate]

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

How to print a date in a regular format?

This is my code:
import datetime
today = datetime.date.today()
print(today)
This prints: 2008-11-22 which is exactly what I want.
But, I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:
import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print(mylist)
This prints the following:
[datetime.date(2008, 11, 22)]
How can I get just a simple date like 2008-11-22?
The WHY: dates are objects
In Python, dates are objects. Therefore, when you manipulate them, you manipulate objects, not strings or timestamps.
Any object in Python has TWO string representations:
The regular representation that is used by print can be get using the str() function. It is most of the time the most common human readable format and is used to ease display. So str(datetime.datetime(2008, 11, 22, 19, 53, 42)) gives you '2008-11-22 19:53:42'.
The alternative representation that is used to represent the object nature (as a data). It can be get using the repr() function and is handy to know what kind of data your manipulating while you are developing or debugging. repr(datetime.datetime(2008, 11, 22, 19, 53, 42)) gives you 'datetime.datetime(2008, 11, 22, 19, 53, 42)'.
What happened is that when you have printed the date using print, it used str() so you could see a nice date string. But when you have printed mylist, you have printed a list of objects and Python tried to represent the set of data, using repr().
The How: what do you want to do with that?
Well, when you manipulate dates, keep using the date objects all long the way. They got thousand of useful methods and most of the Python API expect dates to be objects.
When you want to display them, just use str(). In Python, the good practice is to explicitly cast everything. So just when it's time to print, get a string representation of your date using str(date).
One last thing. When you tried to print the dates, you printed mylist. If you want to print a date, you must print the date objects, not their container (the list).
E.G, you want to print all the date in a list :
for date in mylist :
print str(date)
Note that in that specific case, you can even omit str() because print will use it for you. But it should not become a habit :-)
Practical case, using your code
import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist[0] # print the date object, not the container ;-)
2008-11-22
# It's better to always use str() because :
print "This is a new day : ", mylist[0] # will work
>>> This is a new day : 2008-11-22
print "This is a new day : " + mylist[0] # will crash
>>> cannot concatenate 'str' and 'datetime.date' objects
print "This is a new day : " + str(mylist[0])
>>> This is a new day : 2008-11-22
Advanced date formatting
Dates have a default representation, but you may want to print them in a specific format. In that case, you can get a custom string representation using the strftime() method.
strftime() expects a string pattern explaining how you want to format your date.
E.G :
print today.strftime('We are the %d, %b %Y')
>>> 'We are the 22, Nov 2008'
All the letter after a "%" represent a format for something:
%d is the day number (2 digits, prefixed with leading zero's if necessary)
%m is the month number (2 digits, prefixed with leading zero's if necessary)
%b is the month abbreviation (3 letters)
%B is the month name in full (letters)
%y is the year number abbreviated (last 2 digits)
%Y is the year number full (4 digits)
etc.
Have a look at the official documentation, or McCutchen's quick reference you can't know them all.
Since PEP3101, every object can have its own format used automatically by the method format of any string. In the case of the datetime, the format is the same used in
strftime. So you can do the same as above like this:
print "We are the {:%d, %b %Y}".format(today)
>>> 'We are the 22, Nov 2008'
The advantage of this form is that you can also convert other objects at the same time.
With the introduction of Formatted string literals (since Python 3.6, 2016-12-23) this can be written as
import datetime
f"{datetime.datetime.now():%Y-%m-%d}"
>>> '2017-06-15'
Localization
Dates can automatically adapt to the local language and culture if you use them the right way, but it's a bit complicated. Maybe for another question on SO(Stack Overflow) ;-)
import datetime
print datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
Edit:
After Cees' suggestion, I have started using time as well:
import time
print time.strftime("%Y-%m-%d %H:%M")
The date, datetime, and time objects all support a strftime(format) method,
to create a string representing the time under the control of an explicit format
string.
Here is a list of the format codes with their directive and meaning.
%a Locale’s abbreviated weekday name.
%A Locale’s full weekday name.
%b Locale’s abbreviated month name.
%B Locale’s full month name.
%c Locale’s appropriate date and time representation.
%d Day of the month as a decimal number [01,31].
%f Microsecond as a decimal number [0,999999], zero-padded on the left
%H Hour (24-hour clock) as a decimal number [00,23].
%I Hour (12-hour clock) as a decimal number [01,12].
%j Day of the year as a decimal number [001,366].
%m Month as a decimal number [01,12].
%M Minute as a decimal number [00,59].
%p Locale’s equivalent of either AM or PM.
%S Second as a decimal number [00,61].
%U Week number of the year (Sunday as the first day of the week)
%w Weekday as a decimal number [0(Sunday),6].
%W Week number of the year (Monday as the first day of the week)
%x Locale’s appropriate date representation.
%X Locale’s appropriate time representation.
%y Year without century as a decimal number [00,99].
%Y Year with century as a decimal number.
%z UTC offset in the form +HHMM or -HHMM.
%Z Time zone name (empty string if the object is naive).
%% A literal '%' character.
This is what we can do with the datetime and time modules in Python
import time
import datetime
print "Time in seconds since the epoch: %s" %time.time()
print "Current date and time: ", datetime.datetime.now()
print "Or like this: ", datetime.datetime.now().strftime("%y-%m-%d-%H-%M")
print "Current year: ", datetime.date.today().strftime("%Y")
print "Month of year: ", datetime.date.today().strftime("%B")
print "Week number of the year: ", datetime.date.today().strftime("%W")
print "Weekday of the week: ", datetime.date.today().strftime("%w")
print "Day of year: ", datetime.date.today().strftime("%j")
print "Day of the month : ", datetime.date.today().strftime("%d")
print "Day of week: ", datetime.date.today().strftime("%A")
That will print out something like this:
Time in seconds since the epoch: 1349271346.46
Current date and time: 2012-10-03 15:35:46.461491
Or like this: 12-10-03-15-35
Current year: 2012
Month of year: October
Week number of the year: 40
Weekday of the week: 3
Day of year: 277
Day of the month : 03
Day of week: Wednesday
Use date.strftime. The formatting arguments are described in the documentation.
This one is what you wanted:
some_date.strftime('%Y-%m-%d')
This one takes Locale into account. (do this)
some_date.strftime('%c')
This is shorter:
>>> import time
>>> time.strftime("%Y-%m-%d %H:%M")
'2013-11-19 09:38'
# convert date time to regular format.
d_date = datetime.datetime.now()
reg_format_date = d_date.strftime("%Y-%m-%d %I:%M:%S %p")
print(reg_format_date)
# some other date formats.
reg_format_date = d_date.strftime("%d %B %Y %I:%M:%S %p")
print(reg_format_date)
reg_format_date = d_date.strftime("%Y-%m-%d %H:%M:%S")
print(reg_format_date)
OUTPUT
2016-10-06 01:21:34 PM
06 October 2016 01:21:34 PM
2016-10-06 13:21:34
Or even
from datetime import datetime, date
"{:%d.%m.%Y}".format(datetime.now())
Out: '25.12.2013
or
"{} - {:%d.%m.%Y}".format("Today", datetime.now())
Out: 'Today - 25.12.2013'
"{:%A}".format(date.today())
Out: 'Wednesday'
'{}__{:%Y.%m.%d__%H-%M}.log'.format(__name__, datetime.now())
Out: '__main____2014.06.09__16-56.log'
Simple answer -
datetime.date.today().isoformat()
With type-specific datetime string formatting (see nk9's answer using str.format().) in a Formatted string literal (since Python 3.6, 2016-12-23):
>>> import datetime
>>> f"{datetime.datetime.now():%Y-%m-%d}"
'2017-06-15'
The date/time format directives are not documented as part of the Format String Syntax but rather in date, datetime, and time's strftime() documentation. The are based on the 1989 C Standard, but include some ISO 8601 directives since Python 3.6.
I hate the idea of importing too many modules for convenience. I would rather work with available module which in this case is datetime rather than calling a new module time.
>>> a = datetime.datetime(2015, 04, 01, 11, 23, 22)
>>> a.strftime('%Y-%m-%d %H:%M')
'2015-04-01 11:23'
You need to convert the datetime object to a str.
The following code worked for me:
import datetime
collection = []
dateTimeString = str(datetime.date.today())
collection.append(dateTimeString)
print(collection)
Let me know if you need any more help.
In Python you can format a datetime using the strftime() method from the date, time and datetime classes in the datetime module.
In your specific case, you are using the date class from datetime. You can use the following snippet to format the today variable into a string with the format yyyy-MM-dd:
import datetime
today = datetime.date.today()
print("formatted datetime: %s" % today.strftime("%Y-%m-%d"))
In the following a more complete example:
import datetime
today = datetime.date.today()
# datetime in d/m/Y H:M:S format
date_time = today.strftime("%d/%m/%Y, %H:%M:%S")
print("datetime: %s" % date_time)
# datetime in Y-m-d H:M:S format
date_time = today.strftime("%Y-%m-%d, %H:%M:%S")
print("datetime: %s" % date_time)
# format date
date = today.strftime("%d/%m/%Y")
print("date: %s" % time)
# format time
time = today.strftime("%H:%M:%S")
print("time: %s" % time)
# day
day = today.strftime("%d")
print("day: %s" % day)
# month
month = today.strftime("%m")
print("month: %s" % month)
# year
year = today.strftime("%Y")
print("year: %s" % year)
More directives:
Sources:
Format DateTime in Python
strftime
You can do:
mylist.append(str(today))
Considering the fact you asked for something simple to do what you wanted, you could just:
import datetime
str(datetime.date.today())
For those wanting locale-based date and not including time, use:
>>> some_date.strftime('%x')
07/11/2019
Since the print today returns what you want this means that the today object's __str__ function returns the string you are looking for.
So you can do mylist.append(today.__str__()) as well.
from datetime import date
def today_in_str_format():
return str(date.today())
print (today_in_str_format())
This will print 2018-06-23 if that's what you want :)
You may want to append it as a string?
import datetime
mylist = []
today = str(datetime.date.today())
mylist.append(today)
print(mylist)
For pandas.Timestamps, strftime() can be used e.g.:
utc_now = datetime.now()
For isoformat:
utc_now.isoformat()
For any format e.g.:
utc_now.strftime("%m/%d/%Y, %H:%M:%S")
You can use easy_date to make it easy:
import date_converter
my_date = date_converter.date_to_string(today, '%Y-%m-%d')
A quick disclaimer for my answer - I've only been learning Python for about 2 weeks, so I am by no means an expert; therefore, my explanation may not be the best and I may use incorrect terminology. Anyway, here it goes.
I noticed in your code that when you declared your variable today = datetime.date.today() you chose to name your variable with the name of a built-in function.
When your next line of code mylist.append(today) appended your list, it appended the entire string datetime.date.today(), which you had previously set as the value of your today variable, rather than just appending today().
A simple solution, albeit maybe not one most coders would use when working with the datetime module, is to change the name of your variable.
Here's what I tried:
import datetime
mylist = []
present = datetime.date.today()
mylist.append(present)
print present
and it prints yyyy-mm-dd.
Here is how to display the date as (year/month/day) :
from datetime import datetime
now = datetime.now()
print '%s/%s/%s' % (now.year, now.month, now.day)
import datetime
import time
months = ["Unknown","January","Febuary","Marchh","April","May","June","July","August","September","October","November","December"]
datetimeWrite = (time.strftime("%d-%m-%Y "))
date = time.strftime("%d")
month= time.strftime("%m")
choices = {'01': 'Jan', '02':'Feb','03':'Mar','04':'Apr','05':'May','06': 'Jun','07':'Jul','08':'Aug','09':'Sep','10':'Oct','11':'Nov','12':'Dec'}
result = choices.get(month, 'default')
year = time.strftime("%Y")
Date = date+"-"+result+"-"+year
print Date
In this way you can get Date formatted like this example: 22-Jun-2017
I don't fully understand but, can use pandas for getting times in right format:
>>> import pandas as pd
>>> pd.to_datetime('now')
Timestamp('2018-10-07 06:03:30')
>>> print(pd.to_datetime('now'))
2018-10-07 06:03:47
>>> pd.to_datetime('now').date()
datetime.date(2018, 10, 7)
>>> print(pd.to_datetime('now').date())
2018-10-07
>>>
And:
>>> l=[]
>>> l.append(pd.to_datetime('now').date())
>>> l
[datetime.date(2018, 10, 7)]
>>> map(str,l)
<map object at 0x0000005F67CCDF98>
>>> list(map(str,l))
['2018-10-07']
But it's storing strings but easy to convert:
>>> l=list(map(str,l))
>>> list(map(pd.to_datetime,l))
[Timestamp('2018-10-07 00:00:00')]
maybe the shortest solution, which exactly matches your situation, would be:
mylist.append(str(AnyDate)[:10])
or even shorter, e.g.:
f'{AnyDate}'[:10]
PS: it doesn't need to be today.

Categories

Resources