Efficient way for python date string manipulation - python

I want to turn '07/18/2013' to '07/2013' and there are a lot of these strings to be processed. What would be the most efficient way to do it?
I am thinking of using
''.join(['07/18/2013'[0:3],'07/18/2013'[6:]])

Look into strftime and strptime.
Assuming you start with the string s you can put it into a datetime object using strptime then take that back out into a string with only the necessary fields using strftime. I didn't actually run this code so I don't know if it is perfect, but the idea is here.
temp = datetime.strptime.(s, "%m/%D/%Y")
final = temp.strftime(%m/%Y")
You can find info on the datetime functions here https://docs.python.org/2/library/datetime.html

Use datetime module:
import datetime
print datetime.datetime.strptime("07/18/2013", '%m/%d/%Y').strftime('%m/%Y')

Related

Write numpy datetime64 in ISO 8601 with timezone

How can the time zone be controlled when writing numpy datetime64 objects as an ISO 8601 string? Specifically, I would like the time zone to be "+0000", just like the input below. For this very simple example I just want it to print back the original string.
import numpy
print(numpy.datetime64('2014-03-07T17:52:00.000+0000'))
For me, it returns
2014-03-07T12:52:00.000-0500
I am using python 3.4, numpy 1.9.2, and windows.
This question is similar, but the first two answers don't actually answer the question and the third answer is specific to unix.
s = '2014-03-07T17:52:00.000+0000'
print(numpy.datetime64(s).item().replace(tzinfo=pytz.UTC).isoformat('T'))
Thanks to ShadowRanger for getting me going in the right direction. item gets naive datetime from datetime64, then replace time zone with UTC since I know that's what it is in this case, then get it in ISO format with the 'T' separator.
This should work:
import numpy, time, os
os.environ['TZ'] = 'GMT'
time.tzset()
print(numpy.datetime64('2014-03-07T17:52:00.000+0000'))
based on this stackoverflow answer:
https://stackoverflow.com/a/32764078/5915424

Compare if datetime.timedelta is between two values

I have a datetime.timedelta time object in python (e.g. 00:02:00) I want to check if this time is less than 5 minutess and greater then 1 minute.
I'm not sure how to construct a timedelta object and I'm also not sure if this is the right format to compare times. Would anyone know the most efficient way to do this?
So if you start with a string that's rigorously and precisely in the format 'HH:MM:SS', timedelta doesn't directly offer a string-parsing function, but it's not hard to make one:
import datetime
def parsedelta(hhmmss):
h, m, s = hhmmss.split(':')
return datetime.timedelta(hours=int(h), minutes=int(m), seconds=int(s))
If you need to parse many different variants you'll be better off looking for third-party packages like dateutil.
Once you do have timedelta instance, the check you request is easy, e.g:
onemin = datetime.timedelta(minutes=1)
fivemin = datetime.timedelta(minutes=5)
if onemin < parsedelta('00:02:00') < fivemin:
print('yep')
will, as expected, display yep.

Python script: convert random date formats to fixed yyyy-mm-dd

I'm quite new to python and don't know much about it but i need to make a small script that when someone inputs a date in any format , it would then converts it in to yyyy-mm-dd format.
The script should be able to share elements of the entered date, and identify patterns.
It might be easy and obvious to some but making one by my self is over my head.
Thanks in advance!
This is a difficult task to do yourself; you might want to take a look at dateutil which has a rather robust parse() method that you can use to try and parse arbitrarily formatted date strings.
You can do something like this (not tested)
import locale
import datetime
...
parsedDate = datetime.strptime(your_string, locale.D_FMT)
print datetime.strftime(parsedDate, "%Y-%M-%d")
This assumes that the user will use its own local convention for dates.
You can use strftime for output (your format is "%Y-%M-%d").
For parsing input there's a corresponding function - strptime. But you won't be able to handle "any format". You have to know what you're getting in the first place. Otherwise you wouldn't be able to tell a difference between (for example) American and other dates. What does 01.02.03 mean for example? This could be:
yy.mm.dd
dd.mm.yy
mm.dd.yy

Human-readable datetime interval to datetime.timedelta in Python?

I find myself needing to specify a timespan in a python configuration file a lot.
Is there a way that I can specify a more human readable timeframe (similar to PostgreSQL's Interval syntax) in a python configuration file with stdlib? Or will this require a 3rd party lib?
Clarification I'm not looking for anything in the ConfigParser.ConfigParser stdlib API specifically. I guess what I really need is a way to go from human readable date/time interval to datetime.timedelta value.
I found a good answer to this in an somewhat related question. Turns out the humanfriendly library does that fairly well:
In [1]: import humanfriendly
In [2]: humanfriendly.parse_timespan('1w')
Out[2]: 604800.0
That's in seconds. To get a timedelta object, you can simply load that:
In [3]: from datetime import timedelta
In [4]: timedelta(seconds=humanfriendly.parse_timespan('1w'))
Out[4]: datetime.timedelta(7)
Since humanfriendly also supports converting the other way, you can also do full round trip, which would look like:
In [5]: humanfriendly.format_timespan(timedelta(seconds=humanfriendly.parse_timespan('1w')).total_seconds())
Out[5]: '1 week'
Note how format_timespan does not access timedelta objects, unfortunately: only an integer (seconds).
I don't think there is a standard library module for that. I wrote one that does that. You can install it, or adapt it to your needs.
The module is called pycopia.timespec
It converts strings such as "1day 3min" to seconds, as a float. It's easy to get a datetime.timedelta from that.

Python PIL save file with datetime as name

I'm relatively new to python and know very little syntax, but I'm willing to learn as much as possible. Simply put I want to use the save feature in PIL to save a .png with the file's name being the current date and time. This may be complicated by the fact that I'm not using PIL directly, but through the Videocapture module, but i doubt it. this is my code that works
from VideoCapture import Device
cam = Device()
cam.saveSnapshot('C:\Users\Myname\Dropbox\Foldes\image.png', timestamp=3, boldfont=1, textpos='bc')
Its short, but it does what I need it to.
I realize Datetime will need to be imported, But I can't get the data as the name without errors. yes i have tried the str() command. Any help will be greatly appreciated.
'C:\Users\Myname\Dropbox\Foldes\image.png'
In strings in Python, backslashes have special meaning so you need to treat them differently. You can either use two of them instead of one...
'C:\\Users\\Myname\\Dropbox\\Foldes\\image.png'
...or you can put an r before the string (as long as it doesn't end with a backslash)
r'C:\Users\Myname\Dropbox\Foldes\image.png'
To generate a string containing the current day in YYYY-MM-DD-HH:MM format, we can use the datetime module like this. To format the timestamp differently, consult the documentation here.
import datetime
date_string = datetime.datetime.now().strftime("%Y-%m-%d-%H:%M")
As a shorter alternative, you could use the similar time module instead:
import time
date_string = time.strftime("%Y-%m-%d-%H:%M")
After this, you should just be able to do
cam.saveSnapshot(r'C:\Users\Myname\Dropbox\Foldes\image-' + date_string + '.png',
timestamp=3, boldfont=1, textpos='bc')
to save the image with the datetime in the filename. (I have split the function call over two lines for readability, see this question for some explanation of how this works.)

Categories