Python get micro time from certain date - python

I was browsing the Python guide and some search machines for a few hours now, but I can't really find an answer to my question.
I am writing a switch where only certain files are chosen to be in the a file_list (list[]) when they are modified after a given date.
In my loop I do the following code to get its micro time:
file_time = os.path.getmtime(path + file_name)
This returns me a nice micro time, like this: 1342715246.0
Now I want to compare if that time is after a certain date-time I give up. So for testing purposes, I used 1790:01:01 00:00:00.
# Preset (outside the class/object)
start_time = '1970-01-01 00:00:00'
start_time = datetime.datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S')
start_time = start_time.strftime("%Y-%m-%d %H:%M:%S")
# In my Method this check makes sure I only append files to the list
# that are modified after the given date
if file_time > self.start_time:
file_list.append(file_name)
Of course this does not work, haha :P. What I'm aiming for is to make a micro time format from a custom date. I can only find ClassMethods online that make micro time formats from the current date.

Take a look at Python datetime to microtime. You need the following snippet:
def microtime(dt):
time.mktime(dt.timetuple()) + dt.microsecond / 1000000.0

You can compare datetime.datetime objects by themselves. If you keep start_time as a datetime.datetime object and make file_time a datetime.datetime object, you can successfully do file_time > self.start_time
Take a look at the supported operators in the documentation

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')))

Issue with code when using datetime and timezone

I have a list of strings called 'entries'. Each entry includes a date and time in a format like this: 'Mon Jun 15 17:52:03 2015'
I'm parsing the dates/times from each entry with regex and then I need to put them into python's datetime format and change the timezone to UTC (which is local time +4 hrs). Here's my code:
from datetime import datetime
import pytz
local = pytz.timezone("Etc/GMT+4")
localdate = [None]*len(entries)
local_dt = [None]*len(entries)
utc_dt = [None]*len(entries)
utdate = [None]*len(entries)
for i in range(len(entries)):
localdate[i] = datetime.strptime(re.search(r'\w{3}\s*?\w{3}\s*?\d{1,2}\s*?
\d{1,2}:\d{2}:\d{2}\s*?\d{4}', entries[i]).group(0), "%c")
local_dt[i] = local.localize(localdate[i], is_dst=None)
utc_dt[i] = local_dt[i].astimezone(pytz.utc)
utdate[i] = utc_dt[i].strftime("%c")
utdate = map(str, utdate)
print utdate
It seems to work well line-by-line if I go through and print each step, but once it gets to the last step it reverts back to the original format of the dates/times rather than the python datetime format of 'yyyy-mm-dd hh:mm:ss'. Anyone know what's wrong?
tl;dr
You're formatting the datetime object into a string with utdate[i] = utc_dt[i].strftime("%c"). The %c code formats the date according to the system's localization settings, not the format you're expecting.
The standard string representation of a datetime object will generate the format you're looking for – you can get a string from str(some_datetime), or print(some_datetime) to print it to the console.
Timezones
This is notoriously hard to keep track of, but you may want to double check which timezone you're using. As is, your code will take an input time and give an output time that's 4 hours earlier. If I'm understanding correctly, you expect it the other way around. You should know that the "Etc" timezones are labelled oppositely for weird reasons, and you may want to change the timezone used. It's a different question, but using a location-based timezone instead of a UTC offset may be a good idea for things like DST support.
Improvements
You can simplify and clarify what you're trying to do here with a few changes. It makes it a bit more "Pythonic" as well.
input_format = '%a %b %d %H:%M:%S %Y' # Change 1
converted_entries = [] # Change 2
for entry in entries: # Change 3
local_date = datetime.strptime(entry, input_format) # Change 1 (continued)
# Change 4
localized_date = local.localize(local_date)
utc_date = localized_date.astimezone(pytz.utc)
converted_entries.append(utc_date)
utdate = map(str, converted_entries)
print utdate
Changes
Use a strftime/strptime formatter. strftime and strptime are designed to parse strings, ordinarily regular expressions shouldn't be needed to process them first. The same goes for output formats – if specific format is needed that's not provided with a built-in method like datetime.isoformat, use a formatter.
In Python there's no need to initialize a list a length ahead of time (or with None). list_var = [] or list_var = list() will give you an empty list that will expand on demand.
Typically it's best and simplest to just iterate over a list, rather than jump through hoops to get a loop counter. It's more readable, and ultimately less to remember.
If you do need a counter, use enumerate, e.g.: for i, entry in enumerate(entries):
Use scoped variables. Temporary values like localdate and localdt can just be kept inside the for loop. Technically it's wasting memory, but more importantly it keeps the code simpler and more encapsulated.
If the values are needed for later, then do what I've done with the converted_entries list. Initialize it outside the loop, then just append the value to the list each time through.
No need for counter variables:
localized_dates = []
for # omitted ...
localized_date = local.localize(local_date)
localized_dates.append(localized_date)
I hope that's helpful for you. The beauty of Python is that it can be pretty simple, so just embrace it 😀

Python and module - date

If I don't have access to the Python time module, how would I determine the number of days that have passed since I was born? That is, within the code, how many days old I am?
The code I am trying to understand better is this:
import time
start = raw_input(“Enter the time stamp in seconds: “)
start = float(start)
end = time.time()
elapsed = end - start
st_elapsed = time.gmtime(elapsed)
print "\n"
hours_mins_secs = time.strftime("%H:%M:%S", st_elapsed)
print "Elapsed time in HH:MM:SS ->", hours_mins_secs, "\n"
Now, I looked to the site https://docs.python.org/2/library/time.html
but I didn't find the alternative related to time, without using module time.
My goal is understand better this code.
This sounds like a homework question. You should give us what you've done so far and we will help you. SO users are not your personal coders.
(No criticism intended)

Elegant way to adjust date timezones in Python

I'm based in the UK, and grappling with summer time BST and timezones.
Here's my code:
TIME_OFFSET = 1 # 0 for GMT, 1 for BST
def RFC3339_to_localHHMM(input):
# Take an XML date (2013-04-08T22:35:00Z)
# return e.g. 08/04 23:35
return (datetime.datetime.strptime(input, '%Y-%m-%dT%H:%M:%SZ') +
datetime.timedelta(hours=TIME_OFFSET)).strftime('%d/%m %H:%M')
Setting a variable like this feels very wrong, but I can't find any elegant way to achieve the above without hideous amounts of code. Am I missing something, and is there no way to (for example) read the system timezone?
To convert UTC to given timezone:
from datetime import datetime
import pytz
local_tz = pytz.timezone("Europe/London") # time zone name from Olson database
def utc_to_local(utc_dt):
return utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz)
rfc3339s = "2013-04-08T22:35:00Z"
utc_dt = datetime.strptime(rfc3339s, '%Y-%m-%dT%H:%M:%SZ')
local_dt = utc_to_local(utc_dt)
print(local_dt.strftime('%d/%m %H:%M')) # -> 08/04 23:35
See also How to convert a python utc datetime to a local datetime using only python standard library?.
You seem to be asking a few separate questions here.
First, if you only care about your own machine's current local timezone, you don't need to know what it is. Just use the local-to-UTC functions. There are a few holes in the API, but even if you can't find the function you need, you can always just get from local to UTC or vice-versa by going through the POSIX timestamp and the fromtimestamp and utcfromtimestamp methods.
If you want to be able to deal with any timezone, see the top of the docs for the difference between aware and naive objects, but basically: an aware object is one that knows its timezone. So, that's what you need. The problem is that, as the docs say:
Note that no concrete tzinfo classes are supplied by the datetime module. Supporting timezones at whatever level of detail is required is up to the application.
The easiest way to support timezones is to install and use the third-party library pytz.
Meanwhile, as strftime() and strptime() Behavior sort-of explains, strptime always returns a naive object. You then have to call replace and/or astimezone (depending on whether the string was a UTC time or a local time) to get an aware object imbued with the right timezone.
But, even with all this, you still need to know what local timezone you're in, which means you still need a constant. In other words:
TIMEZONE = pytz.timezone('Europe/London')
def RFC3339_to_localHHMM(input):
# Take an XML date (2013-04-08T22:35:00Z)
# return e.g. 08/04 23:35
utc_naive = datetime.datetime.strptime(input, '%Y-%m-%dT%H:%M:%SZ')
utc = utc_naive.replace(pytz.utc)
bst = utc.astimezone(TIMEZONE)
return bst.strftime('%d/%m %H:%M')
So, how do you get the OS to give you the local timezone? Well, that's different for different platforms, and Python has nothing built in to help. But there are a few different third-party libraries that do, such as dateutil. For example:
def RFC3339_to_localHHMM(input):
# Take an XML date (2013-04-08T22:35:00Z)
# return e.g. 08/04 23:35
utc = datetime.datetime.strptime(input, '%Y-%m-%dT%H:%M:%SZ')
bst = utc.astimezone(dateutil.tz.tzlocal())
return bst.strftime('%d/%m %H:%M')
But now we've come full circle. If all you wanted was the local timezone, you didn't really need the timezone at all (at least for your simple use case). So, this is only necessary if you need to support any timezone, and also want to be able to, e.g., default to your local timezone (without having to write two copies of all of your code for the aware and naive cases).
(Also, if you're going to use dateutil in the first place, you might want to use it for more than just getting the timezone—it can basically replacing everything you're doing with both datetime and pytz.)
Of course there are other options besides these libraries—search PyPI, Google, and/or the ActiveState recipes.
If you want to convert a UTC input into a local time, regardless of which timezone you're in, try this:
def utctolocal(input):
if time.localtime()[-1] == 1: st=3600
else: st=0
return time.localtime(time.time()-time.mktime(time.gmtime())+time.mktime(time.localtime(time.mktime(time.strptime(input, '%Y-%m-%dT%H:%M:%SZ'))))+st)
Quite long code, but what it does is it simply adds the difference between time.gmtime() and time.localtime() to the time tuple created from the input.
Here's a function I use to do what I think you want. This assumes that the input is really a gmt, or more precisely, a utc datetime object:
def utc_to_local(utc_dt):
'''Converts a utc datetime obj to local datetime obj.'''
t = utc_dt.timetuple()
secs = calendar.timegm(t)
loc = time.localtime(secs)
return datetime.datetime.fromtimestamp(time.mktime(loc))
Like you said, this relies on the system time zone, which may give you shaky results, as some of the comments have pointed out. It has worked perfectly for me on Windows, however.
A simple function to check if a UCT corresponds to BST in London or GMT (for setting TIME_OFFSET above)
import datetime
def is_BST(input_date):
if input_date.month in range(4,9):
return True
if input_date.month in [11,12,1,2]:
return False
# Find start and end dates for current year
current_year = input_date.year
for day in range(25,32):
if datetime.datetime(current_year,3,day).weekday()==6:
BST_start = datetime.datetime(current_year,3,day,1)
if datetime.datetime(current_year,10,day).weekday()==6:
BST_end = datetime.datetime(current_year,10,day,1)
if (input_date > BST_start) and (input_date < BST_end):
return True
return False

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