Format datestamp in python - python

Using import datetime in python, is it possible to take a formatted time/date string such as:
2012-06-21 20:36:11
And convert it into an object that I can then use to produce a newly formatted string such as:
21st June 2012 20:36

import time
s = '2012-06-21 20:36:11'
t = time.strptime(s, '%Y-%m-%d %H:%M:%S')
print time.strftime('%d %B %Y %H:%M', t)
returns
21 June 2012 20:36
If you really want the 'st',
def nth(n):
return str(n) + nth.ext[int(n)%10]
nth.ext = ['th', 'st', 'nd', 'rd'] + ['th']*6
print nth(t.tm_mday) + time.strftime(' %B %Y %H:%M', t)
gets you
21st June 2012 20:36

You want datetime.strptime, it parses text into datetimes:
>>> d = "2012-06-21 20:36:11"
>>> datetime.datetime.strptime(d, "%Y-%m-%d %H:%M:%S")
datetime.datetime(2012, 6, 21, 20, 36, 11)
Formatting the date in the way you want is almost doable:
>>> datetime.datetime.strftime(t, "%d %B %Y %H:%m")
'21 June 2012 20:06'

Related

time data 'May 10 2021' does not match format '%m %d %Y'

I am having trouble printing a formatted time object produced from a string
This is my code:
date_time_str = 'May 10 2021'
date_time_obj = datetime. strptime(date_time_str, '%m %d %Y')
print("The type of the date is now", type(date_time_obj))
This is the error:
ValueError: time data 'May 10 2021' does not match format '%m %d %Y'
As per This link, for a month in the Month format, you need to use %B , and for a month in the Mth format ('Apr','Jun') , use %b.
You were using %m, which is used for numerical numbers.
The below works as an example:
import time
import datetime
from time import strptime
print("hello world")
date_time_str = 'May 10 2021'
date_time_obj = strptime(date_time_str, '%B %d %Y')
print("The type of the date is now", date_time_obj)
You can also use datetime parser from dateutil package with fuzzy parsing which is extremely useful when parsing non-standard datetime formats or parsing dates from text:
from dateutil import parser as dps
>>> a = 'Today is 11th of June 2021'
>>> d = dps.parse(a, fuzzy=True)
>>> d
Out[5]: datetime.datetime(2021, 6, 11, 0, 0)
>>> b = 'May 10, 2021'
>>> c = dps.parse(b, fuzzy=True)
>>> c
Out[8]: datetime.datetime(2021, 5, 10, 0, 0)

How to convert UTC/extended format to datetime in Python

I want to convert datetime in %Y-%m-%d,
so from Sat, 17 Apr 2021 16:17:00 +0100 to 17-04-2021
def convertDatetime(data):
test_datetime = data
data_new_format = datetime.datetime.strptime(test_datetime,'%- %Y %M %d')
print(data_new_format)
convertDatetime("Sat, 17 Apr 2021 16:17:00 +0100")
but it say me: '-' is a bad directive in format '%- %Y %M %d'
The format you specify '%- %Y %M %d' (1) contains an incorrect specifier - as the error says, and also (2) completely does not match the data you want to convert. The format you pass to strptime() must match the way the data looks, not the way you want it to look.
>>> data="Sat, 17 Apr 2021 16:17:00 +0100"
>>> format = "%a, %d %b %Y %H:%M:%S %z"
>>> datetime.datetime.strptime(data, format)
datetime.datetime(2021, 4, 17, 16, 17, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600)))
To reformat the datetime the way you want, you need a second call, to strftime():
>>> datetime.datetime.strptime(data, format).strftime("%Y-%m-%d")
'2021-04-17'

Python datetime strptime() does not match format

I get the following error in which you can see the time data and the format I am using
time data '20:07:35 EEDT Wed Mar 31 2021' does not match format '%H:%M:%S %Z %a %b %d %Y'
I used the directives from here and I see that the format matches the description of each directive.
Can you see what is the issue here?
import datetime
time = '20:07:35 EEDT Wed Mar 31 2021'
time = time.replace('EEDT', '+0300')
datetime.datetime.strptime(time, '%H:%M:%S %z %a %b %d %Y')
you can map the abbreviated time zone to a IANA time zone name by dateutil's parser:
import dateutil
s = '20:07:35 EEDT Wed Mar 31 2021'
tzmapping = {"EEDT": dateutil.tz.gettz('Europe/Athens'),
"EEST": dateutil.tz.gettz('Europe/Athens')} # add more if needed...
dtobj = dateutil.parser.parse(s, tzinfos=tzmapping)
that will give you
dtobj
# >>> datetime.datetime(2021, 3, 31, 20, 7, 35, tzinfo=tzfile('Europe/Athens'))
dtobj.utcoffset()
# >>> datetime.timedelta(seconds=10800) # UTC+3
Note that timedelta arithmetic works correctly, i.e. includes DST changes:
from datetime import timedelta
dtobj -= timedelta(7) # DST change: dtobj is now EEST, UTC+2
dtobj.utcoffset()
# >>> datetime.timedelta(seconds=7200)
Problem is with EEDT. If you ignore EEDT(quickfix, not ideal), then your code may look like:
text = '20:07:35 EEDT Wed Mar 31 2021';
fmt = '%H:%M:%S EEDT %a %b %d %Y';
datetime.strptime(text, fmt)
--edit--
parsing datetime with timezone is difficult to pure datetime module. I'm not big expert, but pytz or python-datetutil should be good choice, according to this page: https://medium.com/#nqbao/python-timezone-and-daylight-savings-e511a0093d0
For those who are interested in different approach for similar, like GMT and BST or EEST and EEDT, it can be represented like this:
import datetime
try:
Time1 = datetime.datetime.strptime(DropTm,"%a %b %d %H:%M:%S GMT %Y")
except:
Time1 = datetime.datetime.strptime(DropTm,"%a %b %d %H:%M:%S BST %Y")
In your situation it will be:
import datetime
try:
Time1 = datetime.datetime.strptime(SomeValue,"%H:%M:%S EEDT %a %b %d %Y")
except:
Time1 = datetime.datetime.strptime(SomeValue,"%H:%M:%S EEST %a %b %d %Y")
Where is "SomeValue" your data!!
It did worked for me and do not need any other libraries! Good Luck with coding!!!

Date does not match parsed format in python

the following snippet of code throws an error stating "ValueError: time data 'Dec 25 2017' does not match format '%b /%d /%y'"
import datetime,time
from Hall import Hall
Fd=input("Enter Start time\n")
d1 = datetime.datetime.strptime(Fd, '%b /%d /%y')
Sd=input("Enter the End time\n")
d2 = datetime.datetime.strptime(Sd, '%b /%d /%y')
cost=int(input("Enter the cost per day\n"))
x = Hall(d1,d2,cost)
The format i want to use is Dec 25 2017. Would appreciate any help.
The date that you input, namely Dec 25 2017, needs to match the format you specify in strptime.
Try the following, and enter the same input Dec 25 2017:
Fd=input("Enter Start time\n")
d1 = datetime.datetime.strptime(Fd, '%b %d %Y')
Sd=input("Enter the End time\n")
d2 = datetime.datetime.strptime(Sd, '%b %d %Y')
There are two issues with your date format
You have some extra / that you don't expect
And to input the complete year you need to use %Y (capital Y)
Try this:
datetime.datetime.strptime(Sd, '%b %d %Y')

Python strftime %A fixed length

I am using the following date format:
d.strftime("%A, %d %B %Y %H:%m")
and since the length of the weekday (%A) changes,
I would like to always print the weekday with
10 characters, pad spaces to the left, and align it right.
Something like
d.strftime("10%A, %d %B %Y %H:%m")
What is the simplest way?
str.rjust(10) does exactly that:
s = d.strftime('%A').rjust(10) + d.strftime(', %d %B %Y %H:%M')
It is likely that you want %M (minutes), not %m (months) in your format string as #Ahmad pointed out.
In Python 3.6+, to get a more concise version, one can abuse nested f-strings:
>>> f"{f'{d:%A}':>10}, {d:%d %B %Y %H:%M}"
' Friday, 15 December 2017 21:31'
Prefer standard time formats such as rfc 3339:
>>> from datetime import datetime
>>> datetime.utcnow().isoformat() + 'Z'
'2016-02-05T14:00:43.089828Z'
Or rfc 2822:
>>> from email.utils import formatdate
>>> formatdate(usegmt=True)
'Fri, 05 Feb 2016 14:00:51 GMT'
instead.
How about this:
d.strftime("%A") + " " * (10 - len(d.strftime("%A")) + "," + d.strftime("%d %B %Y %H:%m")
Jack
This is roughly equivalent to jfs's answer, but you can use .format() to make it slightly shorter:
s = '{:>10}, {:%d %B %Y %H:%m}'.format(d.strftime('%A'), d)
or if you're putting more than just the date into the string:
args = {
'weekday' = d.strftime('%A'),
'date' = d,
'foo' = some_other_stuff(),
'bar' = 17.5422,
}
s = '{weekday:>10}, {date:%d %B %Y %H:%m} {foo} {bar:>3.2f}'.format(**args)

Categories