Python Change how string is printed - python

I have a string output from another program that shows the date as
16/05/03 # (YY/MM/DD)
and I wish to change it to
03/05/16 #(DD/MM/YY)
and here is how the date is supplied
(date = info[4].replace('"', '')
i have tried
dates = str(date)[::-1]
but that gave me an output of
40/50/61
not quite what I wanted
any ideas using a minimal code as possible?

>>> '/'.join('16/05/03'.split('/')[::-1])
'03/05/16'
or
>>> '/'.join(reversed('16/05/03'.split('/')))
'03/05/16'
or using datetime library:
>> from datetime import datetime
>>> datetime.strftime(datetime.strptime('16/05/03', '%y/%m/%d'), '%d/%m/%y')
'03/05/16'

Using datetime give you alot more control with changing the format to suite what you want.
import datetime
d = datetime.strptime('16/05/03', '%y/%m/%d')
print d.strftime('%d/%m/%y')

Related

Can't produce a certain format of date when I use a customized date instead of now

I'm trying to format a date to a customized one. When I use datetime.datetime.now(), I get the right format of date I'm after. However, my intention is to get the same format when I use 1980-01-22 instead of now.
import datetime
date_string = "1980-01-22"
item = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
print(item)
Output I get:
2021-05-04T09:52:04.010Z
How can I get the same format of date when I use a customized date, as in 1980-01-22 instead of now?
MrFuppes suggestion in the comments is the shortest way to accomplish your date conversion and formatting use case.
Another way is to use the Python module dateutil. This module has a lot of flexibility and I use it all the time.
Using dateutil.parser.parse:
from dateutil.parser import parse
# ISO FORMAT
ISO_FORMAT_MICROS = "%Y-%m-%dT%H:%M:%S.%f%z"
# note the format of these strings
date_strings = ["1980-01-22",
"01-22-1980",
"January 22, 1980",
"1980 January 22"]
for date_string in date_strings:
dt = parse(date_string).strftime(ISO_FORMAT_MICROS)
# strip 3 milliseconds for the output and add the ZULU time zone designator
iso_formatted_date = f'{dt[:-3]}Z'
print(iso_formatted_date)
# output
1980-01-22T00:00:00.000Z
1980-01-22T00:00:00.000Z
1980-01-22T00:00:00.000Z
1980-01-22T00:00:00.000Z
Using dateutil.parser.isoparse:
from dateutil.parser import isoparse
from dateutil.tz import *
dt = isoparse("1980-01-22").isoformat(timespec="milliseconds")
iso_formatted_date = f'{dt}Z'
print(iso_formatted_date)
# output
1980-01-22T00:00:00.000Z
Is this what your trying to achieve?
date_string = "1980-01-22"
datetime.datetime.strptime(date_string, "%Y-%m-%d").isoformat(timespec="milliseconds")
Output
'1980-01-22T00:00:00.000'

Conversion of date 8-DEC-17 to 08/12/2017 is giving 07/12/2017 in python

I'm trying to format the datetime in python, and this is what I was trying:
import time
datestr = "8-DEC-17"
v=time.strptime(datestr,"%d-%b-%y")
l = time.mktime(v)
print(time.strftime("%d/%m/%y ", time.gmtime(l)))
The output of this code is :
07/12/17 which is not the one I want
I am expecting : 08/12/17
You can use datetime which is a bit shorter and gives the result you want:
from datetime import datetime
datetime.strptime(datestr, "%d-%b-%y").strftime("%d/%m/%y")
According to https://docs.python.org/3/library/time.html#time.mktime, mktime() is the inverse function of localtime(). So, you need to use localtime() instead of gmtime() to print the result:
print(time.strftime("%d/%m/%y ", time.localtime(l)))
outputs 08/12/17
from dateutil.parser import parse
datestr = "8-DEC-17"
dt = parse(datestr)
print(dt.strftime("%d/%m/%y"))

Date and time with numbers in python?

I need to get the current date with numbers, like that: 14:45:35:233 08.05.2016. I didn't find a function for that in the time module, is there any short way to do that?
It sounds like you want parse from specific date time format to another one. Maybe it'd be what you looking for, take a look:
>>> import datetime
>>> strdate = '14:45:35:233 08.05.2016'
>>> dt = datetime.datetime.strptime(strdate, '%H:%M:%S:233 %d.%m.%Y')
>>> dt.strftime('%Y-%m-%d')
'2016-05-08'
Use strftime() and get whatever format you need.
Use strftime to format time.
datetime.datetime.now() will give current time.
To get the time in "Hours:Minutes:Seconds:Microseconds Date.Month.Year " Format use strftime("%H:%M:%S:%f %d.%m.%Y")
import datetime
a=datetime.datetime.now()
a.strftime("%H:%M:%S:%f %d.%m.%Y")
Output
'16:50:54:238874 08.05.2016'
Use this :
>>> import datetime
>>> import time
>>> ts = time.time()
>>> datetime.datetime.fromtimestamp(ts).strftime('%H.%M.%S %d.%m.%Y')
Output :
'18.20.06 08.05.2016'

Python datetime to string without microsecond component

I'm adding UTC time strings to Bitbucket API responses that currently only contain Amsterdam (!) time strings. For consistency with the UTC time strings returned elsewhere, the desired format is 2011-11-03 11:07:04 (followed by +00:00, but that's not germane).
What's the best way to create such a string (without a microsecond component) from a datetime instance with a microsecond component?
>>> import datetime
>>> print unicode(datetime.datetime.now())
2011-11-03 11:13:39.278026
I'll add the best option that's occurred to me as a possible answer, but there may well be a more elegant solution.
Edit: I should mention that I'm not actually printing the current time – I used datetime.now to provide a quick example. So the solution should not assume that any datetime instances it receives will include microsecond components.
If you want to format a datetime object in a specific format that is different from the standard format, it's best to explicitly specify that format:
>>> import datetime
>>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
'2011-11-03 18:21:26'
See the documentation of datetime.strftime() for an explanation of the % directives.
Starting from Python 3.6, the isoformat() method is flexible enough to also produce this format:
datetime.datetime.now().isoformat(sep=" ", timespec="seconds")
>>> import datetime
>>> now = datetime.datetime.now()
>>> print unicode(now.replace(microsecond=0))
2011-11-03 11:19:07
In Python 3.6:
from datetime import datetime
datetime.now().isoformat(' ', 'seconds')
'2017-01-11 14:41:33'
https://docs.python.org/3.6/library/datetime.html#datetime.datetime.isoformat
This is the way I do it. ISO format:
import datetime
datetime.datetime.now().replace(microsecond=0).isoformat()
# Returns: '2017-01-23T14:58:07'
You can replace the 'T' if you don't want ISO format:
datetime.datetime.now().replace(microsecond=0).isoformat(' ')
# Returns: '2017-01-23 15:05:27'
Yet another option:
>>> import time
>>> time.strftime("%Y-%m-%d %H:%M:%S")
'2011-11-03 11:31:28'
By default this uses local time, if you need UTC you can use the following:
>>> time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
'2011-11-03 18:32:20'
Keep the first 19 characters that you wanted via slicing:
>>> str(datetime.datetime.now())[:19]
'2011-11-03 14:37:50'
I usually do:
import datetime
now = datetime.datetime.now()
now = now.replace(microsecond=0) # To print now without microsecond.
# To print now:
print(now)
output:
2019-01-13 14:40:28
Since not all datetime.datetime instances have a microsecond component (i.e. when it is zero), you can partition the string on a "." and take only the first item, which will always work:
unicode(datetime.datetime.now()).partition('.')[0]
As of Python 3.6+, the best way of doing this is by the new timespec argument for isoformat.
isoformat(timespec='seconds', sep=' ')
Usage:
>>> datetime.now().isoformat(timespec='seconds')
'2020-10-16T18:38:21'
>>> datetime.now().isoformat(timespec='seconds', sep=' ')
'2020-10-16 18:38:35'
We can try something like below
import datetime
date_generated = datetime.datetime.now()
date_generated.replace(microsecond=0).isoformat(' ').partition('+')[0]
>>> from datetime import datetime
>>> dt = datetime.now().strftime("%Y-%m-%d %X")
>>> print(dt)
'2021-02-05 04:10:24'
f-string formatting
>>> import datetime
>>> print(f'{datetime.datetime.now():%Y-%m-%d %H:%M:%S}')
2021-12-01 22:10:07
This I use because I can understand and hence remember it better (and date time format also can be customized based on your choice) :-
import datetime
moment = datetime.datetime.now()
print("{}/{}/{} {}:{}:{}".format(moment.day, moment.month, moment.year,
moment.hour, moment.minute, moment.second))
I found this to be the simplest way.
>>> t = datetime.datetime.now()
>>> t
datetime.datetime(2018, 11, 30, 17, 21, 26, 606191)
>>> t = str(t).split('.')
>>> t
['2018-11-30 17:21:26', '606191']
>>> t = t[0]
>>> t
'2018-11-30 17:21:26'
>>>
You can also use the following method
import datetime as _dt
ts = _dt.datetime.now().timestamp()
print("TimeStamp without microseconds: ", int(ts)) #TimeStamp without microseconds: 1629275829
dt = _dt.datetime.now()
print("Date & Time without microseconds: ", str(dt)[0:-7]) #Date & Time without microseconds: 2021-08-18 13:07:09
Current TimeStamp without microsecond component:
timestamp = list(str(datetime.timestamp(datetime.now())).split('.'))[0]

calculating the next day from a "YYYYMMDD" formatted string

How can I calculate the next day from a string like 20110531 in the same YYYYMMDD format? In this particular case, I like to have 20110601 as the result. Calculating "tomorrow" or next day in static way is not that tough, like this:
>>> from datetime import date, timedelta
>>> (date.today() + timedelta(1)).strftime('%Y%m%d')
'20110512'
>>>
>>> (date(2011,05,31) + timedelta(1)).strftime('%Y%m%d')
'20110601'
But how can I use a string like dt = "20110531" to get the same result as above?
Here is an example of how to do it:
import time
from datetime import date, timedelta
t=time.strptime('20110531','%Y%m%d')
newdate=date(t.tm_year,t.tm_mon,t.tm_mday)+timedelta(1)
print newdate.strftime('%Y%m%d')
>>> from datetime import datetime
>>> print datetime.strptime('20110531', '%Y%m%d')
2011-05-31 00:00:00
And then do math on that date object as you show in your question.
The datetime library docs.
You are most of the way there! along with the strftime function which converts a date to a formatted string, there is also a strptime function which converts back the other way.
To solve your problem you can just replace date.today() with strptime(yourDateString, '%Y%m%d').
ED: and of course you will also have to add strptime to the end of your from datetime import line.

Categories