How to get time value in milliseconds from a date object python? - 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

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

Python what is the correct timefomat for: 2018-11-13T20:20:39+00:00

I need to get a now() timestamp like this following: 2018-11-13T20:20:39+00:00 What is the correct format string for this?
To get an isoformat() string with time zone offset (the +00:00 at the end of the string) you need to supply a tzinfo object when constructing the datetime. the easiest way to do this is with the pytz library - pytz.timezone("UTC") returns the tzinfo for UTC.
There's another issue though, which is that technically that string doesn't quite match default isoformat() output because it has no microseconds. So a full example for the output requested would be:
import datetime
import pytz
datetime.datetime.now(tz=pytz.timezone("UTC")).replace(microsecond=0).isoformat()
This appears to be the isoformat.
You could use
import datetime as dt
# Get current time in utc
# Because the datetime object is timezone aware the +00:00 will be printed
current_time = dt.datetime.now(dt.timezone.utc)
# timespec will round the solution upto seconds
iso_string = current_time.isoformat(timespec="seconds")
print(iso_string)
will print 2019-11-19T19:51:46+00:00.

Timestamp to non UTC Datetime object is substracting hours twice

I have the following timestamp 1550588656 which translates to 2019-02-19 15:04:16+00:00 in UTC time convention.
I want to convert it to my country's time convention (UTC or GMT -3 in this time of the year) so it should translate to 2019-02-19 12:04:16+00:00
I have read on other SO questions that first I have to convert the timestamp to an UTC aware Datetime object and then localize it, I'm doing it like this
# string format time
naive_datetime = datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
# string parse time
naive_datetime = datetime.strptime(naive_datetime, "%Y-%m-%d %H:%M:%S")
# make naive Datetime object UTC aware
utc_datetime = naive_datetime.replace(tzinfo=pytz.UTC)
So now it's not a naive Datetime object, from here I should be able to localize it to my country's timezone. In Python that is pytz.timezone('America/Santiago')
So it should go something like this
cltime = pytz.timezone('America/Santiago')
local_datetime = utc_datetime.astimezone(cltime)
But I'm getting 2019-02-19 09:04:16-03:00 (UTC or GTM -6 ) as a result and I don't know why.
Can someone explain? My intuition tells me it's probably a simple thing I'm not looking at, but I've spent some minutes in it and I haven't been able to tell yet.
If you look at the documentation for fromtimestamp:
Return the local date and time corresponding to the POSIX timestamp
So the problem is that it is already doing a conversion from UTC to the local time, and you're doing it a second time.
First of all you have epoc time (UTC timestamp). You need to convert it into datetime object (native) which is followed by converting native time to aware time and than finally convert it to your local time.
Convert your timestamp to native datetime object
native_datetime = datetime.fromtimestamp(1550588656)
convert native datetime object to aware time (add timezone info, will add timezone info to native timezone UTC for current)
import pytz
utc_time = native_datetime.replace(tzinfo=pytz.timezone("UTC"))
localising aware datetime to your local datetime
local_time = utc_time.astimezone(pytz.timezone("America/Santiago"))
You can replace "America/Santiago" with your local time zone
I think this would help you to solve your problem. Thanks!

how to decode hbase timestamp value in python?

I am new to hbase and currently I am using hbase-1.2.6. I did the connection to hbase using python script by using happybase package. my question is :
can someone please let me know how to decode timestamp value which is automatically inserted whenever we put any records in table?
1.what is the exact interpretation of timestamp value in hbase?
2.can we convert this timestamp value to yy-mm-dd-hh:mm:ss format?
The timestamp value is the number of milliseconds since the epoch (January 1, 1970 UTC). You can use the python datetime module to manipulate it. Example:
from datetime import datetime as dt
print (dt.fromtimestamp(1511356398000 / 1000))
Output:
2017-11-22 07:13:18
The result is a datetime object in my local time zone. (Central USA) The datetime.fromtimestamp method wants a floating point value that is the time in seconds since the epoch, so divide the time in milliseconds by 1000.
Here is the datetime module reference.

Python Convert a Date Time to just Time

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'

Categories

Resources