Get timestamp in seconds from python's datetime - python

How to get timestamp from the structure datetime? What is right alternative for non-existing datetime.utcnow().timestamp()?

use time, and int to remove the milliseconds
from time import time
int(time())
# 1561043225

import time,datetime
time.mktime(datetime.datetime.today().timetuple())

If you don't have to get timestamp from structure datetime, you can decrease instruction like this
import time
print time.time()

There is another stupid trick - achieve timedelta
(datetime.utcnow()-datetime(1970,1,1,0,0,0)).total_seconds()
found here. Better
(datetime.utcnow()-datetime.fromtimestamp(0)).total_seconds()
And this solution contains subseconds.

If I understand correctly what sort of output you are seeking:
from datetime import datetime
timestamp = datetime.now().strftime("%H:%M:%S")
print(timestamp)
> 11:44:40
EDIT: Appears I misinterpreted your question? You are asking for the naive universal time, then galaxyan's answer is concise.

Related

Python: How to print date format with using the help function?

I would like to print the date format so I dont need to search in the navigator every time I want to print a date like in the following code:
time = now.strftime("%Y-%m-%d %H:%M:%S")
print("time:", time)
I been searching and didn't find any thing about this.
When you run help(the_date.strftime), it doesn't show the possible parameters.
You can see the format codes here - Basic date and time types
The below sample reference:
import time
print("time:{}".format(time.strftime('%Y-%m-%d %H:%M:%S')))

How do I get the full timezone name from a Datetime without importing Time?

I'm trying to display my full time zone along with my current local time.
print "Your current time is {0} {1} ".format(datetime.datetime.now().time(), time.tzname[0])
And the result would look something like:
Your current time is 08:35:45.328000 Pacific Standard Time
The problem is I have to import the Time library (sorry if I call it wrong, I'm coming from C#) along with the Datetime library.
import datetime
import time
I've looked into the naive and aware states of time, but still can't seem to get the desired result.
Is there a way to get the full timezone name (i.e.: Pacific Standard Time) from Datetime without having to import Time?
The example for writing your own local timezone tzinfo class uses (scroll down one page from here) pulls the tzname from time.tzname, so Python doesn't have a better built-in solution to suggest.
You could copy that example LocalTimezone implementation, which would allow the use of the %Z format code for strftime on an aware datetime instance using the LocalTimezone, but that's the best you can do with the built-ins. On a naive datetime the tzname is the empty string, so you need an aware datetime for this to work.

Python2 datetime - Convert epoch time to UTC timestamp with offset

I am using Python 2 due to reasons beyond my control and hence cannot upgrade to Python 3 (which has better support for timezones).
I have an epoch time like 1492464960.53 and I want to convert it into a timestamp like this 2017-04-17T21:36:00.530000+00:00.
I tried using the following code but this does not give the +00:00 part of the timestamp that I also need.
import datetime
created=1492464960.53
time_str = datetime.datetime.utcfromtimestamp(created).isoformat()
print(time_str)
>> 2017-04-17T21:36:00.530000
How can I add the +00:00 part?
Just tried this out and it worked for me.
First to explain why original solution didn't work, from what I understand, the reason isoformat() will not work for above epoch value is because this method requires the object to return something with the 'utcoffset' attribute, however above float/epoch value returns 'None' when I tested it out with this attribute.
The isoformat method may very well work if we weren't dealing with converting a float perhaps.
Anyways, onto the solution:
from datetime import datetime, tzinfo
import pytz
created = 1492464960.53
dt = datetime.utcfromtimestamp(created)
##print results for above 'dt' variable
2017-04-17 21:36:00.530000
dt = dt.replace(tzinfo=pytz.utc)
##print results for above 'dt' variable
2017-04-17 21:36:00.530000+00:00
dt.isoformat()
##print results for above 'dt' variable
'2017-04-17T21:36:00.530000+00:00'
Sorry, not sure what you mean exactly about installing pytz, I just pip installed pytz then added the import statement in my python shell on my local machine.
Not sure this is the best solution, however it seems to have worked so here is the alternative I can offer:
created = 1492464960.53
dt = dt.utcnow().fromtimestamp(created, dt.tzname()).isoformat()
should print
'2017-04-17T14:36:00.530000'
from datetime import time
t = time(00, 00, 00, tzinfo=dt.tzname())
tmstmp = dt.isoformat()+'+'+t.strftime("%M:%S %z")
should print
2017-04-17T21:36:00.530000+00:00

Converting "2013-01-06T22:25:08.733" to "2013-01-06 22:25:08" in python

I have a big .csv file which holds machine log data. One of the fields is timestamp. It stores date and time as shown in the title and I would like to drop the milli seconds and convert it into the format also shown in title. Can anyone help me with that? Im new to Python and Ipython.
Much obliged.
For your special case, this should suffice:
t.replace('T', ' ')[:19]
But I would recommend, that you use the datetime module of the standard library instead, so your time conversion also could be internationalized.
You can use easy_date to make it easy:
import date_converter
new_date = date_converter.string_to_string("2013-01-06T22:25:08.733", "%Y-%m-%dT%H:%M:%S.%f", "%Y-%m-%d %H:%M:%S")

using unix timestamp generate timedelta for babel's format_timedelta

I am not sure I worded that correctly but python and time always confuses me.
This is what I am trying.
Given a unix timestamp (INT) which is definitely in the past (can be seconds ago or years ago) I want to generate a babel format_timedelta
My problem is
Babel format_timedelta takes timedelta as first argument
so I guess I need to generate a timedelta using time.time() (now) and the unix timestamp I have.
I can't figure out the part 2 and I believe there must be an easier/correct way to do this. Please share the best possible way to do this, also I need it to be fast in calculating since I have to use it in a web page.
def format_starttime(value, granularity="day"):
delta = datetime.timedelta(seconds=time.time() - value)
return format_timedelta(delta, granularity)
gives error in date.format_timedelta()
AttributeError: 'module' object has no attribute 'format_timedelta'
import datetime
td = datetime.timedelta(seconds=time.time()-a_unix_timestamp)
Difference between two datetime instances is a timedelta instance.
from datetime import datetime
from babel.dates import format_timedelta
delta = datetime.now() - datetime.fromtimestamp(your_timestamp)
print format_timedelta(delta, locale='en_US')
See datetime module documentation for details and more examples.

Categories