Python Convert a Date Time to just Time - python

I have a field that shows time as 1900-01-01 00:05:00 but I want to show it as just 00:05:00 i.e. just five minutes.
I have been looking at the python documentation and it is driving me crazy. From the question How do I find the time difference between two datetime objects in python? it looks like is should be something do with timedelta but I am not getting any closer to a solution. The question Converting Date/Time to Just Time suggests you can just use a format tag but that is not working for me. I also looked at converting date time to string without success, I know this is something simple but I have looked at hundreds of pages looking for something simple. All help would be appreciated.

Say you have a Datetime object now:
now.time().strftime('%H:%M:%S')

Load the string with strptime() and get the time() component:
>>> from datetime import datetime
>>> s = "1900-01-01 00:05:00"
>>> dt = datetime.strptime(s, "%Y-%m-%d %H:%M:%S")
>>> dt.time().isoformat()
'00:05:00'
Here we are dumping the time with isoformat() in ISO 8601 format, but you can also dump the datetime.time back to string with strftime():
>>> dt.time().strftime("%H:%M:%S")
'00:05:00'

Related

want to convert json timestamp into normal timestamp (CST Hrs) in python

I am downloading a json file containing timestamp using python . But the timestamp i am getting is below format
`2021-04-01T21:43:52.757Z`
Want to convert into normal timestamp (CST Hrs). I also see that the time is increased by 4 hours when i compare the report manually.
`4/1/2021 5:43:53 PM`
The above hours is 4 hrs less when i compare with json file entry. Please advise me.
You need to use python's datetime module to handle this. The Z in the string actually means time zone 0 or UTC time which is 6 hours ahead of CST not 4:
import datetime
date_object = datetime.datetime.strptime(
"2021-04-01T21:43:52.757Z", "%Y-%m-%dT%H:%M:%S.%fZ"
)
date_object = date_object - datetime.timedelta(hours=6)
print(
f"{date_object.month}/{date_object.day}/{date_object.year} {date_object.strftime('%I:%M:%S %p')}"
)
Which will give this output:
4/1/2021 03:43:52 PM
have to use an f string if you want non zero padded dates because its not available in datetime according to the docs
You can use pytz module to deal with time zones directly and not hardcode them if you want. Or if you are on python 3.9 you can use timezone objects to create timezones yourself

Convert json field to datetime in Python

I get time data from API response like '2020-02-25T20:53:06.706401+07:00'. Now I want to convert to %Y-%m-%d %H:%M:%s format. But I do not know exactly standard format of that time data.
Help me find the time format!
In your case you can use datetime.fromisoformat:
from datetime import datetime
datetime_object = datetime.fromisoformat("2020-02-25T20:53:06.706401+07:00")
print(datetime_object.strftime("%Y-%m-%d %H:%M:%s"))
Prints
2020-02-25 20:53:1582656786
Other options:
Use the third party dateutil library
Use datetime.strptime which parses the string according to format
You can convert to a datetime object and then optionally recreate the string in a new format as follows:
from datetime import datetime
d = "2020-02-25T20:53:06.706401+07:00"
dt = datetime.strptime(d, "%Y-%m-%dT%H:%M:%S.%f%z")
# Note the capital S
new = dt.strftime("%Y-%m-%d %H:%M:%S")
However the new value here has lost the timezone offset information. I assume that's OK for you. I also used %S instead of %s since I assume that's really what you want. The lowercase %s wouldn't really make sense, and is also not truly supported by Python.

How do I find date for with hours?

In python, I want to find the date and time and put it inside of a string.
I have tried this:
example = datetime.datetime.now()
print(example)
However it returns the date with the miliseconds. What do I do if i don't want the miliseconds included. Just the date and time formatted like this:
YYYY-MM-DD 00:00:00
Try this:
import datetime
example = datetime.datetime.now()
print(example.strftime("%Y-%d-%m %H:%M:%S"))
You need to format the datetime output using this:
datetime.datetime.now().strftime('%H:%M:%S')
This will give you Hours:Minutes:Seconds
To get the format as per your requirements use:
datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
This will give you date time in YYYY-MM-DD 00:00:00 format without milliseconds.
My output: 2019-11-04 22:09:06
To see more directives: Link
Link says:
You can get the formatted date and time using strftime function. It
accepts a format string that you can use to get your desired output
If I understand your question corretly, somethinig like this should work for you.
from datetime import datetime
now = datetime.now()
date = now.strftime("%m/%d/%Y")
print("date:",date)
It came from here. There are other formatting examples in that post.
Datetime's strftime functionality does exactly what you're looking for.
There is some overview and explanation here:
https://www.programiz.com/python-programming/datetime/strftime
print(example.strftime('%Y-%m-%d %H:%M:%S')) will give you the right answer.
I would also look at the arrow library, as it offers a nice API to work with time.

How to get time value in milliseconds from a date object python?

As part of my new work I need to convert one existing java class to a python one.
person.setDob(String.valueOf(person.getDateOfBirth().getTime()));
Please see the above snippet here how to fetch time in milliseconds from date object in python,
Hope I can use datetime.datetime for this purpose. Please help.
To get a date string with milliseconds (3 decimal places behind seconds), use this:
from datetime import datetime
print datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
OUTPUT 2018-10-04 10:18:32.926
%f is displaying milliseconds
To get milliseconds in python, use the below code.
import datetime
print('Datetime in milliscond using now()',datetime.datetime.now())
print('Datetime in milliscond using utcfromtimestamp()', datetime.datetime.utcfromtimestamp(0))
output looks like below
Datetime in milliscond using now() 2019-03-11 17:34:28.290409
Datetime in milliscond using now() 1970-01-01 00:00:00

Python DateUtil Converting string to a date and time

I'm trying to convert a parameter of type string to a date time. I'm using the dateUtil library
from dateutil import parser
myDate_string="2001/9/1 12:00:03"
dt = parser.parse(myDate_string,dayfirst=True)
print dt
every time i run this i get
2001-09-01 12:00:03
regardless of whether i have dayfirst set as true or Year first set as false. Ideally I just want to have a date in the format DD-MM-YYYY HH:MM:SS. I don't want anything fancy. I am willing to use the datetime library but this doesn't seem to work at all for me. Can anyone give simple expamples of how to convert strings to date time with an explicit format, I'm a noob, so the most basic examples are all i require. I'm using Python 2.7
The problem you're having is that any arguments you pass to parser.parse only affect how the string is parsed, not how the subsequent object is printed.
parser.parse returns a datetime object - when you print it it will just use datetime's default __str__ method. If you replace your last line with
print dt.strftime("%d-%m-%Y %H:%M:%S")
it will work as you expect.
The standard lib (built-in) datetime lib can do this easily.
from datetime import datetime
my_date_string = "2001/9/1 12:00:03"
d = datetime.strptime(my_date_string, "%Y/%m/%d %H:%M:%S")
print d.strftime("%d-%m-%Y %H:%M:%S")

Categories

Resources