--- type: tables title: Table with alternating color rows stylesheet: '/scss/tables/table-alternating-rows.scss' ---


--- layout: post title: JOpt Simple 3.1 released published: 1 category: - Programming ---
JOpt Simple is my Java library for parsing command line options. You can find the changes in this latest release here. Happy parsing!


package vivekn
- Alphabetic
- Public
- All
Type Members
- trait ReadablePretrainedVivekn extends ParamsAndFeaturesReadable[ViveknSentimentModel] with HasPretrained[ViveknSentimentModel]
-
class
ViveknSentimentApproach extends AnnotatorApproach[ViveknSentimentModel] with ViveknSentimentUtils
Trains a sentiment analyser inspired by the algorithm by Vivek Narayanan https://github.com/vivekn/sentiment/.
Trains a sentiment analyser inspired by the algorithm by Vivek Narayanan https://github.com/vivekn/sentiment/.
The algorithm is based on the paper "Fast and accurate sentiment classification using an enhanced Naive Bayes model".
The analyzer requires sentence boundaries to give a score in context. Tokenization is needed to make sure tokens are within bounds. Transitivity requirements are also required.
The training data needs to consist of a column for normalized text and a label column (either
"positive"
or"negative"
).For extended examples of usage, see the Examples and the ViveknSentimentTestSpec.
Example
import spark.implicits._ import com.johnsnowlabs.nlp.base.DocumentAssembler import com.johnsnowlabs.nlp.annotators.Tokenizer import com.johnsnowlabs.nlp.annotators.Normalizer import com.johnsnowlabs.nlp.annotators.sda.vivekn.ViveknSentimentApproach import com.johnsnowlabs.nlp.Finisher import org.apache.spark.ml.Pipeline val document = new DocumentAssembler() .setInputCol("text") .setOutputCol("document") val token = new Tokenizer() .setInputCols("document") .setOutputCol("token") val normalizer = new Normalizer() .setInputCols("token") .setOutputCol("normal") val vivekn = new ViveknSentimentApproach() .setInputCols("document", "normal") .setSentimentCol("train_sentiment") .setOutputCol("result_sentiment") val finisher = new Finisher() .setInputCols("result_sentiment") .setOutputCols("final_sentiment") val pipeline = new Pipeline().setStages(Array(document, token, normalizer, vivekn, finisher)) val training = Seq( ("I really liked this movie!", "positive"), ("The cast was horrible", "negative"), ("Never going to watch this again or recommend it to anyone", "negative"), ("It's a waste of time", "negative"), ("I loved the protagonist", "positive"), ("The music was really really good", "positive") ).toDF("text", "train_sentiment") val pipelineModel = pipeline.fit(training) val data = Seq( "I recommend this movie", "Dont waste your time!!!" ).toDF("text") val result = pipelineModel.transform(data) result.select("final_sentiment").show(false) +---------------+ |final_sentiment| +---------------+ |[positive] | |[negative] | +---------------+
- See also
SentimentDetector for an alternative approach to sentiment detection
-
class
ViveknSentimentModel extends AnnotatorModel[ViveknSentimentModel] with HasSimpleAnnotate[ViveknSentimentModel] with ViveknSentimentUtils
Sentiment analyser inspired by the algorithm by Vivek Narayanan https://github.com/vivekn/sentiment/.
Sentiment analyser inspired by the algorithm by Vivek Narayanan https://github.com/vivekn/sentiment/.
The algorithm is based on the paper "Fast and accurate sentiment classification using an enhanced Naive Bayes model".
This is the instantiated model of the ViveknSentimentApproach. For training your own model, please see the documentation of that class.
The analyzer requires sentence boundaries to give a score in context. Tokenization is needed to make sure tokens are within bounds. Transitivity requirements are also required.
For extended examples of usage, see the Examples and the ViveknSentimentTestSpec.
- See also
SentimentDetector for an alternative approach to sentiment detection
- trait ViveknSentimentUtils extends AnyRef
Value Members
-
object
ViveknSentimentModel extends ReadablePretrainedVivekn with Serializable
This is the companion object of ViveknSentimentModel.
This is the companion object of ViveknSentimentModel. Please refer to that class for the documentation.


New
Owner
First Name
[error]
Last Name
[error]
Address
[error]
City
[error]
Telephone
[error]
Add Owner
Update Owner


| Event type |
Total in last complete hour
to
|
Total in last complete day
to
|
|---|---|---|
Formatting of JSON results in the browser
For a more convenient rendering of JSON results consider using a browser extension such as JSONView.
Mangling of messages to events
Square cube doesn't support '.' characters in event names or in JSON property keys. Hence all '.' characters in message type names are replaced with '_' characters when used as an event type in square cube. '.' characters are also replaced with '_' characters in header key names and all property keys in the payload. If the message payload isn't JSON then no payload will be present on the event in square cube.
Example event query with a filter over headers
error(payload).eq(headers.appName,'RedGate.Internal.RedGateToSalesforce.Service').eq(headers.log_level,'Error')&start=2015-07-18T00:00:00Z&stop=2015-07-20T00:00:00ZNote that multiple filters can be applied, here we're using two .eq filters and a date range. Multiple filters are always applied using logical AND. The full list of filters available are described here.
Example event query with sub-string filter over payload property
download_started(payload).re(payload.productName,'SQL')&start=2015-07-19T22:00:00Z&stop=2015-07-20T00:00:00ZThe .re filter is a actually a regular expression filter, but without any regex syntax it acts as a sub-string filter.
Example metric query
distinct(embargoing_failure(payload.ipAddress).re(payload.message,'determine country'))&step=864e5&start=2015-07-15T00:00:00Z&stop=2015-07-20T00:00:00ZThis queries for the number of IP addresses where we failed to discern the country to work-out whether they're embargoed per day. The full list of roll-up methods available are described here. Event filters can be applied too, here we're using the .re filter again.
Metric steppings square cube supports
1e4 (10 seconds) 6e4 (1 minute) 3e5 (5 minutes) 36e5 (1 hour) 864e5 (1 day)
Querying for absent properties
Sadly there is no filter in square cube that allows you to include only events where a certain property is null or absent. Performing an event query which will return a property will only return those events which actually have that property, others will be omitted. e.g. example(payload) will only return example events which actually have a payload.


First of all, just getting to the theater presents difficulties. Leaving a home equipped with a TV and a video recorder isn't an attractive idea on a humid, cold, or rainy
Swift Running and Fitness provides a proven system that will set you up for success
"Since using Swift Fitness I'm skinnier and I can run faster. Ashley is amazing.
Each session is an hour long, sessions may have up to 3 people.
Ready to start? Let's go. We'd love to hear from you.
(815) 978-9785
swiftrunning.fit@gmail.com


[% WRAPPER "default_statistics_page_wrapper.html" %]
Distribution of Phantom peak quality tags
Legend
- Dark green: quality tag is 2
- Green: quality tag is 1
- Yellow: quality tag is 0
- Orange: quality tag is -1
- Red: quality tag is -2
- Black: run failed
Within each category the bars refer to
[% FOR dataset IN datasets %]
- [% dataset.title %]
[% END %]
respectively.
Distribution of Phantom peaks NSC values
All NSC values
Narrow peaks only
Broad peaks only
[% END %]


--- title: 'Use GPT and Whisper to Build Your Own Voice Assistant' author: Pablo Cánovas Tourné date: '2023-03-23' slug: gpt-whisper-build-your-own-voice-assistant output: blogdown::html_page: highlight: tango categories: - Python - Post subtitle: 'A step-by-step guide to building your own personal AI-powered voice assistant in python, with two tasty flavors: console and Streamlit!' summary: "With the power of GPT and Whisper models, you can create a virtual assistant that is tailored to your needs. Reading this article, you'll learn how to record and transcribe audio, translate text, generate responses with GPT, and play responses out loud using text-to-speech synthesis."  The rise of AI is happening at a faster pace than ever and virtual assistants are quickly becoming a ubiquitous part of our digital lives. Remember Siri and Alexa? They were the jewel in the crown not that long ago and now they are biting the dust against the power of GPT models.
In this blog post, we’ll show you how to build a virtual assistant using GPT and Whisper APIs. These powerful tools allow you to record user voice, transcribe or translate on-the-fly if necessary, and generate a response using OpenAI’s advanced natural language processing capabilities. We’ll take you through the steps of building the bot in two different flavors - an interactive console-based app and a browser-based version powered by Streamlit.
Before you can start, you need to make sure you have the right tools and environment set up. I recommend to set up a virtual environment with pipenv
so all dependencies are managed automatically from the Pipefile included in the Github repository. Below are the steps you can follow to set up your environment:
git clone https://github.com/PabloCanovas/chatgpt-whisper-streamlit-voice-assistant gpt_voice_assistant
pipenv
installed to manage dependencies, then go ahead: pip install pipenv --user
cd gpt_voice_assistant
and by running: pipenv install
which will install dependencies based on Pipfile.lock
file.Manually manage the OpenAI api key is necessary. You will need to create a new file called myapikeys.py
with this line inside: OPENAI_KEY = "my-apikey-goes-here"
, and obviously use your key for that.
You’ll need to define several helper functions that will be used throughout your program, including functions for recording, playing, and transcribing audio among others. Now, we are going to overview them all before showing the main program.
The first step in building your virtual assistant is to record the user’s voice. You can do this using the record_audio_manual
function:
def record_audio_manual(filename, sr=44100):
input(" ** Press enter to start recording **")
audio = sd.rec(int(10 * sr), samplerate=sr, channels=2)
input(" ** Press enter to stop recording **")
sd.stop()
write(filename, sr, audio)
When you call the function, it will prompt the user to press enter to start and stop recording. Once the user stops recording, the audio is saved to the specified file using the write
function from scipy
. It records audio for a fixed maximum duration of 10 seconds by default. Change as needed.
Once you have the user’s voice recorded, you can move on to transcribing it using the Whisper API.
The next step is to transcribe the user’s voice into text. You can do this using the transcribe_audio
function provided, which uses the Whisper API to transcribe the audio. It’s surprisingly easy:
def transcribe_audio(filename):
audio_file = open(filename, "rb")
transcript = openai.Audio.transcribe("whisper-1", audio_file)
audio_file.close()
return transcript
When you call the function, it reads the audio file into memory, calls the openai.Audio.transcribe
function to transcribe the audio using the Whisper API, and returns the resulting transcript.
Also, if you wish to speak to your assistant in a language other than English, you can easily do so by calling the translate_audio
function instead.
def translate_audio(filename):
audio_file = open(filename, "rb")
translation = openai.Audio.translate("whisper-1", audio_file)
audio_file.close()
return translation
Once you have the user’s voice transcribed let’s send it to GPT.
The next step in building this cool assistant is to generate a response to the user’s input using GPT. You can do this using the OpenAI GPT API, which, as everybody already know, allows you to generate human-like text based on a given prompt. It really couldn’t be much easier. Here’s how:
bot = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=messages)
response = bot.choices[0].text
The openai.ChatCompletion.create
function takes two arguments: the name of the GPT model to use (in this case, “gpt-3.5-turbo”), and a list of messages exchanged between the user and the virtual assistant so far. This is important because GPT retains all the conversation context to answer the questions, being this a key aspect of why it works so well. When you call the function, it generates a response to the most recent message from the user, which you can access using the bot.choices[0].text
attribute.
Once you have the response generated by GPT, you can play it out loud on the speakers using the say
function provided in the code. Here’s what it looks like:
def say(text):
p = multiprocessing.Process(target=pyttsx3.speak, args=(text,))
p.start()
while p.is_alive():
if keyboard.is_pressed('enter'):
p.terminate()
else:
continue
p.join()
This function uses the pyttsx3
library I talked about in this other article to generate a speech audio file from the text, and plays it out loud on the speakers using multiprocessing
. The function also listens for the “enter” key, and terminates the speech if it is pressed.
If GPT’s response is particularly long, you might want a way to stop the playback mid-way through. This is where the multithreading capabilities of Python come in.
In Python, multiprocessing
allows you to run multiple threads simultaneously, making it possible to perform several actions at the same time. In the say
function, we use it to play the speech audio file and listen for user input at the same time.
By working this way, we can ensure that the speech doesn’t block the main thread of the program. This means that even if the speech is too verbose or the user is no longer interested in the answer, he can still interact with the program and interrupt it if needed.
Before going for a browser-based app, you may want to start by building an interactive console-based program that you can run on your local machine. This will allow you to quickly test and iterate on your virtual assistant without the need for a web server or browser.
Using the building blocks described above, here’s how my assistant looks like:
import openai
import myapikeys
from text_speech_utils import *
openai.api_key = myapikeys.OPENAI_KEY
input_audio_filename = 'input.wav'
messages = [{"role": "system", "content": "You are a helpful assistant."}]
def main():
while True:
record_audio_manual(input_audio_filename)
transcription = transcribe_audio(input_audio_filename) # if we want to speak in another language we would use 'translate_audio' function
messages.append({"role": "user", "content": transcription['text']})
print(f"\n- Me: {transcription['text']}")
bot = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=messages)
response = bot.choices[0].message.content
print(f"- ChatGPT: {response}")
print("\n*** Press enter to interrupt assistant and ask a new question ***\n")
say(response)
if __name__ == '__main__':
main()
In this example, we define the main loop of our program using a while loop that listens for user input. Inside the loop, we simply record, transcribe (or translate), send the text to openAI and playback the response.
And there you have it! In barely 50 lines of code we have built a fully functional voice assistant which can be used to learn about new topics, inspire yourself with new cooking recipes or plan detailed workouts that fit your own objectives.
In addition to the console-based program, you can also create an small web app with Streamlit. Streamlit is a Python library that allows you to build interactive web apps with just a few lines of code.
Here’s a snapshot of what my small app looks like:
And this is the code that generates it:
import streamlit as st
import pandas as pd
import openai
import myapikeys
from text_speech_utils import *
openai.api_key = myapikeys.OPENAI_KEY
input_audio_filename = 'input.wav'
output_audio_filename = 'chatgpt_response.wav'
output_conversation_filename = 'ChatGPT_conversation.txt'
# Initialize app
if 'messages' not in st.session_state:
st.session_state['messages'] = [{"role": "system", "content": "You are a helpful assistant."}]
st.title("My awesome personal assistant")
sec = st.slider("Select number of seconds of recording", min_value=2, max_value=8, value=5)
# Record audio + transcribe with Whisper + get GPT3 response
if st.button('Record audio'):
st.write("Recording...")
record_audio(input_audio_filename, sec)
transcription = transcribe_audio(input_audio_filename)
st.write(f"Me: {transcription['text']}")
st.session_state['messages'].append({"role": "user", "content": transcription['text']})
bot = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=st.session_state['messages'])
response = bot.choices[0].message.content
st.write(f"GPT: {response}")
save_text_as_audio(response, output_audio_filename)
play_audio(output_audio_filename)
st.session_state['messages'].append({"role": "assistant", "content": response})
st.download_button(label="Download conversation",
data = pd.DataFrame(st.session_state['messages']).to_csv(index=False).encode('utf-8'),
file_name=output_conversation_filename)
Where I added a slider to define the numbers of seconds you want to record, and the possibility of downloading the full conversation at the end.
Also, I’ve used a couple of different functions than in the example above: save_text_as_audio
and play_audio
. The reason is simply because I couldn’t make the say
function work on the Streamlit app, probably because of something related to the multiprocessing thing.
You can find all the code here.
In this blog post, I’ve shown you how to build a virtual assistant using OpenAI GPT and Whisper APIs. I have taken you through the steps of building an interactive console-based program and a browser-based app using Streamlit.
A possible next step could be deploying the app to the web, maybe on Heroku, AWS or GCP. In case you are going for it, keep me in the loop! I’d be happy to know this could be useful to anyone.
Happy building!


Ion Channels in C. elegans
ChannelWorm
OpenWorm is an open source project dedicated to creating the first virtual organism in a computer.
View
Dataset
Ion Channel Dataset
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Praesentium, vel! Eius pariatur nemo expedita.
View
Reference Management
OpenWorm scholar
OpenWorm is an open source project dedicated to creating the first virtual organism in a computer.
ViewModeling
Ion Channel Modeler
- Full Access
- Source Files
- 100 User Accounts
- 1 Year License
- Phone & Email Support
Searching
Open Scholar
- Full Access
- Source Files
- 500 User Accounts
- 3 Years License
- Phone & Email Support


Since Java 8, Java supports functional programming. If the parameter type of a method is a functional interface, a lambda expression or a method reference can be substituted for it. A functional interface is an interface that has only one abstract method. Lambda expressions and method references are discussed later.
Download movies.txt and copy it to the src directory.
Create a movie class as shown below.
package net.java_school.examples; public class Movie { private final String title; private final int releaseDate; private final double userRatings; public Movie(String title, int releaseDate, double userRatings) { this.title = title; this.releaseDate = releaseDate; this.userRatings = userRatings; } public String getTitle() { return title; } public int getReleaseDate() { return releaseDate; } public double getUserRatings() { return userRatings; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(this.getTitle()); sb.append(","); sb.append(this.getReleaseDate()); sb.append(","); sb.append(this.getUserRatings()); return sb.toString(); } }
title indicates the movie title, releaseDate indicates the release date, and userRatings indicates the user rating.
Create a functional interface like this:
package net.java_school.examples; public interface Predicate<T> { boolean test(T t); }
Predicate is a function that takes a value and returns true or false. Create a class that implements the Predicate functional interface as follows:
package net.java_school.examples; public class Rated8OrAbovePredicate implements Predicate<Movie> { @Override public boolean test(Movie movie) { return movie.getUserRatings() >= 8.0; } }
Create a class for testing as follows:
package net.java_school.examples; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.List; public class MovieTest { static List<Movie> filterMovies(List<Movie> movies, Predicate<Movie> p) { List<Movie> result = new ArrayList<>(); for (Movie movie : movies) { if (p.test(movie)) { result.add(movie); } } return result; } public static void main(String[] args) throws Exception { String fileName = "./src/movies.txt"; String str = null; List<Movie> movies = new ArrayList<>(); try (BufferedReader br = new BufferedReader(new FileReader(fileName))) { while ((str = br.readLine()) != null) { String[] arr = str.split(","); Movie movie = new Movie(arr[0], Integer.parseInt(arr[1]), Double.parseDouble(arr[2])); movies.add(movie); } } List<Movie> result = filterMovies(movies, new Rated8OrAbovePredicate()); for (Movie movie : result) { System.out.println(movie); } } }
Butch Cassidy And The Sundance Kid,1969,8.1 Blade Runner 2049,2017,8.1 Twelve Monkeys,1995,8.0 The Dark Knight,2008,9.0 The Dark Knight Rises,2012,8.4 The Terminator,1984,8.0 Terminator 2,1991,8.5 Roman Holiday,1953,8.1 Ben Hur,1959,8.1 The Battle of Algiers,1966,8.1 Jaws,1975,8.0 Blade Runner,1982,8.2 The Silence Of The Lambs,1991,8.6 Scent of a Woman,1992,8.0 The Shawshank Redemption,1994,9.3 Heat,1995,8.2 Knockin On Heavens Door,1997,8.0 Eternal Sunshine of the Spotless Mind,2004,8.3 No Country for Old Men,2007,8.1 Rocky,1976,8.1
Compare the result with the original movie.txt. The result is highlighted.
Butch Cassidy And The Sundance Kid,1969,8.1 Lucy,2014,6.4 Asphalte,2015,7.1 Spy,2015,7.0 Blade Runner 2049,2017,8.1 Small Town Crime,2017,6.6 The Commuter,2018,6.3 Flashdance,1983,6.1 Midnight Run,1988,7.6 Twelve Monkeys,1995,8.0 As Good As It Gets,1997,7.7 Collateral,2004,7.5 Choke,2008,6.5 The Dark Knight,2008,9.0 The Dark Knight Rises,2012,8.4 Infinitely Polar Bear,2014,7.0 Mission Impossible 3,2006,6.9 Mission Impossible 4,2011,7.4 The Terminator,1984,8.0 Terminator 2,1991,8.5 Flight,2012,7.3 Our Brand Is Crisis,2015,6.1 The Rewrite,2014,6.2 The Secret Life of Walter Mitty,2013,7.3 Waterloo Bridge,1940,7.8 Roman Holiday,1953,8.1 Ben Hur,1959,8.1 The Battle of Algiers,1966,8.1 Love Story,1970,6.9 Jaws,1975,8.0 Operation Daybreak,1975,7.1 Blade Runner,1982,8.2 The Silence Of The Lambs,1991,8.6 Thelma and Louise,1991,7.4 Scent of a Woman,1992,8.0 The Shawshank Redemption,1994,9.3 Heat,1995,8.2 Jerry Maguire,1996,7.6 Knockin On Heavens Door,1997,8.0 28 Days,2000,6.0 Unbreakable,2000,7.3 Secondhand Lion,2003,7.6 Eternal Sunshine of the Spotless Mind,2004,8.3 Little Miss Sunshine,2006,7.8 No Country for Old Men,2007,8.1 The Lookout,2007,7.0 Doubt,2008,7.5 The Bank Job,2008,7.3 The Wrestler,2008,7.9 Agora,2009,7.2 Morning Glory,2010,6.5 Foxfire,2012,6.2 Drive,2011,7.8 Walk of Shame,2014,6.0 Truth,2015,6.8 Tschick,2016,7.0 Creed,2015,7.6 Rocky,1976,8.1
So far, this is about Java 7.
In Java 8, you can instantiate a functional interface with a lambda expression. In MovieTest's main method, you can get the same result by modifying the List<Movie> result = filterMovies(movies, new Rated8OrAbovePredicate()) statement as below:
List<Movie> result = filterMovies(movies, (Movie movie) -> movie.getUserRatings() >= 8.0);
A lambda expression instance is not created from Rated8OrAbovePredicate. To verify, delete the class Rated8OrAbovePredicate and test again.
Since Java 8, a functional interface like Predicate has been added to the API. Add the Predicate interface of the API to the import statement, delete the Predicate interface we created, and test again.
import java.util.function.Predicate;
An instance of a functional interface can also be created as a method reference. Add the following method to Movie.java to test the method reference.
public static boolean isPopular(Movie movie) { return movie.getUserRatings() >= 8.0; }
In MovieTest's main method, modify
List<Movie> result = filterMovies(movies, (Movie movie) -> movie.getUserRatings() >= 8.0);
to
List<Movie> result = filterMovies(movies, Movie::isPopular); and test again.
Java 8 provides a number of functional interfaces that can be used in a variety of situations in the java.util.function package. Functional interfaces are classified into three categories: Predicate, Consumer, and Function.
java.util.function.Consumer<T> interface defines an accept abstract method that accepts a generic T object and returns void.
java.util.function.Function<T,R> interface defines an apply abstract method that accepts a generic T abject and return generic R.
A functional interface acts as a signature of a lambda expression or method reference.
The Predicate interface provides the default methods: negate(), and(), or(). Add the negate() default method as shown below and test again.
Predicate<Movie> popularMovies = Movie::isPopular; List<Movie> result = filterMovies(movies, popularMovies.negate());
Lucy,2014,6.4 Asphalte,2015,7.1 Spy,2015,7.0 Small Town Crime,2017,6.6 The Commuter,2018,6.3 Flashdance,1983,6.1 Midnight Run,1988,7.6 As Good As It Gets,1997,7.7 Collateral,2004,7.5 Choke,2008,6.5 Infinitely Polar Bear,2014,7.0 Mission Impossible 3,2006,6.9 Mission Impossible 4,2011,7.4 Flight,2012,7.3 Our Brand Is Crisis,2015,6.1 The Rewrite,2014,6.2 The Secret Life of Walter Mitty,2013,7.3 Waterloo Bridge,1940,7.8 Love Story,1970,6.9 Operation Daybreak,1975,7.1 Thelma and Louise,1991,7.4 Jerry Maguire,1996,7.6 28 Days,2000,6.0 Unbreakable,2000,7.3 Secondhand Lion,2003,7.6 Little Miss Sunshine,2006,7.8 The Lookout,2007,7.0 Doubt,2008,7.5 The Bank Job,2008,7.3 The Wrestler,2008,7.9 Agora,2009,7.2 Morning Glory,2010,6.5 Foxfire,2012,6.2 Drive,2011,7.8 Walk of Shame,2014,6.0 Truth,2015,6.8 Tschick,2016,7.0 Creed,2015,7.6
Add the and() default method as shown below and test again.
Predicate<Movie> popularMovies = Movie::isPopular; List<Movie> result = filterMovies(movies, popularMovies.negate().and(m -> m.getReleaseDate() > 2015));
Small Town Crime,2017,6.6 The Commuter,2018,6.3 Tschick,2016,7.0
Because of type inference, (Movie m) -> m.getReleaseDate() > 2015 can be abbreviated to m -> m.getReleaseDate() > 2015.
The Eclipse project with source code for the examples is in the following zip file.
functionalProgramming.zip
~/functionalProgramming$ cd src/net/java_school/examples/ ~/functionalProgramming/src/net/java_school/examples$ javac -d ../../../../bin *.java ~/functionalProgramming/src/net/java_school/examples$ cd - ~/functionalProgramming$ java -cp ./bin net.java_school.examples.MovieTest Small Town Crime,2017,6.6 The Commuter,2018,6.3 Tschick,2016,7.0


Cultural Blog - Motivation
How does life look through the 'pleasure, passion and purpose' lens?
Sounds like fun! Seriously though, this was an interesting insight. The idea that our normal behaviour is to pursue the least valuble of these was quite a revalation. Of course the real trick is to reprogramme oneself to invert these priorities.
From the 'discovering values and higher purpose' exercise, What are your core values?
It's very hard for me to instantly write down some words which will stand the test of time here. So for now here is my interim answer: My core values are honesty, integrity, fairness, friendship, and a sense of humour.
What do you stand for?
As above...but here goes...I stand for the idea that we should try to leave this place no worse than we found it! Balance your rights with your obligations, try to help those who need a little help, do your best to generally improve things. Of course it's easier said than done but that's the general idea!
How did you find the resilience ideas and meditation exercise?
This also sounds generally good but I find it pretty hard to instantly recall a relevant episode from my life to use as an example to meditate on. Often I seem to recall such an episode days or weeks later! This means that is will take quite a while to fully test out this procedure.
Any other musings?
I like the fact that they frequently refer to a scientific basis for their claims. I would otherwise be inclined to dismiss some of this stuff as "feel good quackery"! However it's also important to remember that different people will draw different conclusions from the same piece of research especially if the design of the experiment allows for some ambiguity.


With the countless online resources available to consumers, the car-buying process has undergone many changes. Instead of going straight to the dealership, shoppers flock to the Internet for information. In fact, a survey of 10,000 consumers revealed that
looking to buy a new car were using digital technology in some form to do research on the purchase.


Be bold in stating your key points. Put them in a list:
Improve your image by including an image.
Add a link to your favorite Web site. Break up your page with a horizontal rule or two.
© Wiley Publishing, 2011
Finally, link to another page in your own Web site.
You can hit ESC or click outside to close the modal. Give it a go to see the reverse transition.
wwwwwwww


[ aws ]
This is the CloudTrail API Reference. It provides descriptions of actions, data types, common parameters, and common errors for CloudTrail.
CloudTrail is a web service that records AWS API calls for your AWS account and delivers log files to an Amazon S3 bucket. The recorded information includes the identity of the user, the start time of the AWS API call, the source IP address, the request parameters, and the response elements returned by the service.
Note
As an alternative to the API, you can use one of the AWS SDKs, which consist of libraries and sample code for various programming languages and platforms (Java, Ruby, .NET, iOS, Android, etc.). The SDKs provide a convenient way to create programmatic access to AWSCloudTrail. For example, the SDKs take care of cryptographically signing requests, managing errors, and retrying requests automatically. For information about the AWS SDKs, including how to download and install them, see the Tools for Amazon Web Services page .
See the AWS CloudTrail User Guide for information about the data that is included with each AWS API call listed in the log files.


TRACK STUDENTS
01PESB2020
02PESB2020
03PESB2020
04PESB2020
05PESB2020
06PESB2020
Choose a Route id, and click the "Submit" button to send input to the server.


A comparative study of the social and economic impacts of the explosion in horizontal well drilling aka. Fracking. Our studies goal is to understand both the positive and negative impacts of fracking on a state.
Our study explores the explosion of fracking between the years of 2009 and 2016. We compare median home price, median household income, and normalized violent crime. Additionaly we look at the impact of Earthquakes beieved to be caused by fracking over the same period of time.


{% extends 'bootstrap_base.html' %} {% block app_content %}
There are no rounds. Please play the game to create schedule.


BLAZE A film review by Mark R. Leeper Copyright 1989 Mark R. Leeper
Capsule review: Not as well-hyped as other films this holiday season, BLAZE is still a front-runner for plaudits with a solid performance by Lolita Davidovitch managing to steal the show from Paul Newman. Rating: high +2.
For a while the most interesting films of the year were released during the summer. These days the period with the best films is the winter holiday season so they are fresh in people's minds for Oscar nominations. released with very little fanfare, BLAZE is certainly a contender. BLAZE manages to be a serious film and at the same time delightful, not an easy feat. History records that Governor Earl Long of Louisiana, brother to empire- builder Huey Long, was himself a crafty politician and an eccentric character. Earl risked his career to continue a long-standing affair with a notorious stripper, Blaze Starr. BLAZE is the story of Blaze Starr's career, Earl and Blaze's relationship, and Louisiana politics.
The story starts with Blaze (played by Lolita Davidovitch) leaving the Appalachian hill country and going to New Orleans to find work. She is tricked into becoming a stripper, but once she gets used to it she becomes a major New Orleans attraction. Once she meets the Governor (played by Paul Newman) they start spending time together. At some point unclear this stops being social climbing on Blaze's part and becomes a deeply felt, mutually supportive love. The wilder and crazier Earl gets, the more loyalty Blaze is able to muster. At first Earl is enough of a politician to support the rights of blacks and sell it as racism to a constituency that will buy only racism. When he can no longer fool the racists he continues to support equality, knowing it may be political suicide. His political enemies retaliate by using his undeniable eccentricities against him in the press. Blaze does not always understand Earl, but she unfailingly knows what Earl needs.
With an actor of Paul Newman's stature acts as eccentrically as Earl Long, a virtual unknown of a co-star runs the risk of going totally unnoticed. That was now what happened at all. If anything, Davidovitch walked away with the film. A Yugoslav by birth and a naturalized Canadian, she is convincing as a touch but gentle woman from Appalacia with an ability to hold audience attention that goes beyond her physical attraction. Davidovitch had small parts in ADVENTURES IN BABYSITTING and THE BIG TOWN, but is unlikely to get any more small parts.
Ron Shelton previously directed BULL DURHAM with good characterization but not such a good story. His BLAZE has a better story and gets a rating of a high +2 on the -4 and +4 scale.
Mark R. Leeper att!mtgzx!leeper<EMAIL_ADDRESS>.
The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.
Please direct comments/criticisms of the review to relevant newsgroups.
Broken URLs inthe reviews are the responsibility of the author.
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
Related links: index of all rec.arts.movies.reviews reviews


@*
* Copyright 2010-2014 Artima, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*@
@(pagename: String)
@genlink(title: String, url: String) = {
@if(pagename == title) {
@title
} else {
@title
}
}
Scalactic User Guide
@genlink("Custom equality", routes.UserGuide.customEquality().url)
@genlink("Default equality", routes.UserGuide.defaultEquality().url)
@genlink("Constrained equality", routes.UserGuide.constrainedEquality().url)
@genlink("Tolerance", routes.UserGuide.tolerance().url)
@genlink("Normalization", routes.UserGuide.normalization().url)
@genlink("The Explicitly DSL", routes.UserGuide.explicitly().url)
@genlink("Or and Every", routes.UserGuide.orAndEvery().url)
@genlink("Requirements", routes.UserGuide.requirements().url)
@genlink("Snapshots", routes.UserGuide.snapshots().url)
@genlink("TimesOnInt", routes.UserGuide.timesOnInt().url)


{{block "extra-head" .}}{{end}}
Remote Adapter
Home
Simulation
Admin
Pprof
Metrics
Healthy
{{template "content" .}}


Princess & Hero is an open source, HTML5 puzzle game, built with Phaser.
https://www.iconfinder.com/icons/111039/key_icon#size=64
Creative Commons (Attribution-Share Alike 3.0 Unported)
Given a color overlay, dropshadow, and added to spritesheet
Shadowhouse Creations Grunge Texture Set
http://webtreats.mysitemyway.com/
Pitched up and chopped


This file contains functions that allow one to decode MPEG-2 compliant video. The code is based on the MPEG-2 specification (ISO/IEC 13818-2). The MPEG-2 decoding is a work in progress, although it works within a limited test range. Throughout the source code, citations are made in cases where an understanding of the code would be helped by looking at an outside source. The format I have chosen is (cite NUM#, LOOKUP_INFO). NUM=1 refers to ISO/IEC: 13818-2, and NUM=2 refers to the reference MPEG implementation written in C, available at [www.mpeg.org].
| Component Summary | |
bit->int
|
MPEGStream_to_rawImageStream
Interprets and decodes a compressed MPEG-2 compliant bit stream, in accordance with the IEEE MPEG-2 specification. |
| Component Detail |
bit->int MPEGStream_to_rawImageStream
<bit>
- An MPEG-2 compliant bit stream of variable length.
<int>
- Outputs a series of images representing the frames of the video. Each image consists of 3 integers for each pixel, with the number of pixels per image equalling the width height of the video. Frames are output in time order, top to bottom, left to right, and RGB color order. width
- The resolution width of the video. This variable is only needed until the StreamIt language supports dynamically reconfiguring splijtoins.
height
- The resolution height of the video. This variable is only needed until the StreamIt language supports dynamically reconfiguring splitjoins.


- enableAccess(AccessibleObject) - Method in class org.mockito.internal.util.reflection.AccessibilityChanger
-
changes the accessibleObject accessibility and returns true if accessibility was changed
- enableClassCache() - Method in class org.mockito.configuration.DefaultMockitoConfiguration
-
- enableClassCache() - Method in interface org.mockito.configuration.IMockitoConfiguration
-
Allow objenesis to cache classes.
- enableClassCache() - Method in class org.mockito.internal.configuration.GlobalConfiguration
-
- EndsWith - Class in org.mockito.internal.matchers
-
- EndsWith(String) - Constructor for class org.mockito.internal.matchers.EndsWith
-
- endsWith(String) - Static method in class org.mockito.Matchers
-
String
argument that ends with the given suffix.
- eq(double, double) - Static method in class org.mockito.AdditionalMatchers
-
double argument that has an absolute difference to the given value that
is less than the given delta details.
- eq(float, float) - Static method in class org.mockito.AdditionalMatchers
-
float argument that has an absolute difference to the given value that is
less than the given delta details.
- eq(boolean) - Static method in class org.mockito.Matchers
-
boolean
argument that is equal to the given value.
- eq(byte) - Static method in class org.mockito.Matchers
-
byte
argument that is equal to the given value.
- eq(char) - Static method in class org.mockito.Matchers
-
char
argument that is equal to the given value.
- eq(double) - Static method in class org.mockito.Matchers
-
double
argument that is equal to the given value.
- eq(float) - Static method in class org.mockito.Matchers
-
float
argument that is equal to the given value.
- eq(int) - Static method in class org.mockito.Matchers
-
int
argument that is equal to the given value.
- eq(long) - Static method in class org.mockito.Matchers
-
long
argument that is equal to the given value.
- eq(short) - Static method in class org.mockito.Matchers
-
short
argument that is equal to the given value.
- eq(T) - Static method in class org.mockito.Matchers
-
Object argument that is equal to the given value.
- Equality - Class in org.mockito.internal.matchers
-
- Equality() - Constructor for class org.mockito.internal.matchers.Equality
-
- equals(Object) - Method in class org.mockito.internal.creation.DelegatingMethod
-
- equals(Object) - Method in class org.mockito.internal.invocation.InvocationImpl
-
- equals(Object) - Method in class org.mockito.internal.invocation.SerializableMethod
-
- equals(Object) - Method in class org.mockito.internal.listeners.NotifiedMethodInvocationReport
-
- Equals - Class in org.mockito.internal.matchers
-
- Equals(Object) - Constructor for class org.mockito.internal.matchers.Equals
-
- equals(Object) - Method in class org.mockito.internal.matchers.Equals
-
- equals(Object) - Method in class org.mockito.internal.util.collections.HashCodeAndEqualsMockWrapper
-
- equals(Object) - Method in class org.mockito.internal.util.collections.HashCodeAndEqualsSafeSet
-
- equals(Object) - Method in class org.mockito.internal.util.reflection.GenericMetadataSupport.TypeVarBoundedType
-
- equals(Object) - Method in class org.mockito.internal.util.reflection.GenericMetadataSupport.WildCardBoundedType
-
- equals(Object) - Method in class org.mockito.internal.util.reflection.InstanceField
-
- EqualsWithDelta - Class in org.mockito.internal.matchers
-
- EqualsWithDelta(Number, Number) - Constructor for class org.mockito.internal.matchers.EqualsWithDelta
-
- ExceptionIncludingMockitoWarnings - Exception in org.mockito.internal.exceptions
-
- ExceptionIncludingMockitoWarnings(String, Throwable) - Constructor for exception org.mockito.internal.exceptions.ExceptionIncludingMockitoWarnings
-
- expandVarArgs(boolean, Object[]) - Static method in class org.mockito.internal.invocation.ArgumentsProcessor
-
- extraInterfaces(Class...) - Method in class org.mockito.internal.creation.MockSettingsImpl
-
- extraInterfaces - Variable in class org.mockito.internal.creation.settings.CreationSettings
-
- extraInterfaces() - Method in class org.mockito.internal.util.reflection.GenericMetadataSupport
-
- extraInterfaces(Class<?>...) - Method in interface org.mockito.MockSettings
-
Specifies extra interfaces the mock should implement.
- extraInterfacesAcceptsOnlyInterfaces(Class<?>) - Method in class org.mockito.exceptions.Reporter
-
- extraInterfacesCannotContainMockedType(Class<?>) - Method in class org.mockito.exceptions.Reporter
-
- extraInterfacesDoesNotAcceptNullParameters() - Method in class org.mockito.exceptions.Reporter
-
- extraInterfacesRequiresAtLeastOneInterface() - Method in class org.mockito.exceptions.Reporter
-
- extraTypeInfoFor(int) - Method in class org.mockito.internal.reporting.PrintSettings
-


| DateTime - A date and time object for Perl |
clone()
year()
ce_year()
era_name()
era_abbr()
christian_era()
secular_era()
year_with_era()
year_with_christian_era()
year_with_secular_era()
month()
month_name()
month_abbr()
day()
day_of_week()
local_day_of_week()
day_name()
day_abbr()
day_of_year()
quarter()
quarter_name()
quarter_abbr()
day_of_quarter()
weekday_of_month()
hour()
am_or_pm()
minute()
second()
fractional_second()
millisecond()
microsecond()
nanosecond()
datetime()
is_leap_year()
week()
week_year()
week_number()
week_of_month()
jd()
, $dt->mjd()
time_zone()
offset()
is_dst()
time_zone_long_name()
time_zone_short_name()
epoch()
hires_epoch()
is_finite()
, $dt->is_infinite()
utc_rd_values()
local_rd_values()
leap_seconds()
utc_rd_as_seconds()
locale()
formatter()
set_year()
, $dt->set_month()
, etc.duration_class()
DateTime - A date and time object for Perl
version 1.20
use DateTime;
$dt = DateTime->new( year => 1964, month => 10, day => 16, hour => 16, minute => 12, second => 47, nanosecond => 500000000, time_zone => 'Asia/Taipei', );
$dt = DateTime->from_epoch( epoch => $epoch ); $dt = DateTime->now; # same as ( epoch => time() )
$year = $dt->year; $month = $dt->month; # 1-12
$day = $dt->day; # 1-31
$dow = $dt->day_of_week; # 1-7 (Monday is 1)
$hour = $dt->hour; # 0-23 $minute = $dt->minute; # 0-59
$second = $dt->second; # 0-61 (leap seconds!)
$doy = $dt->day_of_year; # 1-366 (leap years)
$doq = $dt->day_of_quarter; # 1..
$qtr = $dt->quarter; # 1-4
# all of the start-at-1 methods above have corresponding start-at-0 # methods, such as $dt->day_of_month_0, $dt->month_0 and so on
$ymd = $dt->ymd; # 2002-12-06 $ymd = $dt->ymd('/'); # 2002/12/06
$mdy = $dt->mdy; # 12-06-2002 $mdy = $dt->mdy('/'); # 12/06/2002
$dmy = $dt->dmy; # 06-12-2002 $dmy = $dt->dmy('/'); # 06/12/2002
$hms = $dt->hms; # 14:02:29 $hms = $dt->hms('!'); # 14!02!29
$is_leap = $dt->is_leap_year;
# these are localizable, see Locales section $month_name = $dt->month_name; # January, February, ... $month_abbr = $dt->month_abbr; # Jan, Feb, ... $day_name = $dt->day_name; # Monday, Tuesday, ... $day_abbr = $dt->day_abbr; # Mon, Tue, ...
# May not work for all possible datetime, see the docs on this # method for more details. $epoch_time = $dt->epoch;
$dt2 = $dt + $duration_object;
$dt3 = $dt - $duration_object;
$duration_object = $dt - $dt2;
$dt->set( year => 1882 );
$dt->set_time_zone( 'America/Chicago' );
$dt->set_formatter( $formatter );
DateTime is a class for the representation of date/time combinations, and is part of the Perl DateTime project. For details on this project please see http://datetime.perl.org/. The DateTime site has a FAQ which may help answer many "how do I do X?" questions. The FAQ is at http://datetime.perl.org/wiki/datetime/page/FAQ.
It represents the Gregorian calendar, extended backwards in time before its creation (in 1582). This is sometimes known as the "proleptic Gregorian calendar". In this calendar, the first day of the calendar (the epoch), is the first day of year 1, which corresponds to the date which was (incorrectly) believed to be the birth of Jesus Christ.
The calendar represented does have a year 0, and in that way differs from how dates are often written using "BCE/CE" or "BC/AD".
For infinite datetimes, please see the DateTime::Infinite module.
The DateTime.pm module follows a simple consistent logic for determining whether or not a given number is 0-based or 1-based.
Month, day of month, day of week, and day of year are 1-based. Any
method that is 1-based also has an equivalent 0-based method ending in
"_0". So for example, this class provides both day_of_week()
and
day_of_week_0()
methods.
The day_of_week_0()
method still treats Monday as the first day of
the week.
All time-related numbers such as hour, minute, and second are 0-based.
Years are neither, as they can be both positive or negative, unlike any other datetime component. There is a year 0.
There is no quarter_0()
method.
Some errors may cause this module to die with an error string. This
can only happen when calling constructor methods, methods that change
the object, such as set()
, or methods that take parameters.
Methods that retrieve information about the object, such as year()
or epoch()
, will never die.
All the object methods which return names or abbreviations return data based on a locale. This is done by setting the locale when constructing a DateTime object. If this is not set, then "en_US" is used.
The default time zone for new DateTime objects, except where stated otherwise, is the "floating" time zone. This concept comes from the iCal standard. A floating datetime is one which is not anchored to any particular time zone. In addition, floating datetimes do not include leap seconds, since we cannot apply them without knowing the datetime's time zone.
The results of date math and comparison between a floating datetime and one with a real time zone are not really valid, because one includes leap seconds and the other does not. Similarly, the results of datetime math between two floating datetimes and two datetimes with time zones are not really comparable.
If you are planning to use any objects with a real time zone, it is strongly recommended that you do not mix these with floating datetimes.
If you are going to be doing date math, please read the section How DateTime Math Works.
If $ENV{TZ}
is not set, it may involve reading a number of files in /etc
or elsewhere. If you know that the local time zone won't change while your
code is running, and you need to make many objects for the local time zone, it
is strongly recommended that you retrieve the local time zone once and cache
it:
our $App::LocalTZ = DateTime::TimeZone->new( name => 'local' );
... # then everywhere else
my $dt = DateTime->new( ..., time_zone => $App::LocalTZ );
DateTime itself does not do this internally because local time zones can change, and there's no good way to determine if it's changed without doing all the work to look it up.
Do not try to use named time zones (like "America/Chicago") with dates
very far in the future (thousands of years). The current
implementation of DateTime::TimeZone
will use a huge amount of
memory calculating all the DST changes from now until the future
date. Use UTC or the floating time zone and you will be safe.
Internally, dates are represented the number of days before or after
0001-01-01. This is stored as an integer, meaning that the upper and lower
bounds are based on your Perl's integer size ($Config{ivsize}
).
The limit on 32-bit systems is around 2^29 days, which gets you to year (+/-)1,469,903. On a 64-bit system you get 2^62 days, (+/-)12,626,367,463,883,278 (12.626 quadrillion).
DateTime provide many methods. The documentation breaks them down into groups based on what they do (constructor, accessors, modifiers, etc.).
All constructors can die when invalid parameters are given.
Currently, constructors will warn if you try to create a far future DateTime (year >= 5000) with any time zone besides floating or UTC. This can be very slow if the time zone has future DST transitions that need to be calculated. If the date is sufficiently far in the future this can be really slow (minutes).
All warnings from DateTime use the DateTime
category and can be suppressed
with:
no warnings 'DateTime';
This warning may be removed in the future if the DateTime::TimeZone manpage is made much faster.
This class method accepts parameters for each date and time component: "year", "month", "day", "hour", "minute", "second", "nanosecond". It also accepts "locale", "time_zone", and "formatter" parameters.
my $dt = DateTime->new( year => 1966, month => 10, day => 25, hour => 7, minute => 15, second => 47, nanosecond => 500000000, time_zone => 'America/Chicago', );
DateTime validates the "month", "day", "hour", "minute", and "second", and "nanosecond" parameters. The valid values for these parameters are:
An integer from 1-12.
An integer from 1-31, and it must be within the valid range of days for the specified month.
An integer from 0-23.
An integer from 0-59.
An integer from 0-61 (to allow for leap seconds). Values of 60 or 61 are only allowed when they match actual leap seconds.
An integer >= 0. If this number is greater than 1 billion, it will be normalized into the second value for the DateTime object.
Invalid parameter types (like an array reference) will cause the constructor to die.
The value for seconds may be from 0 to 61, to account for leap seconds. If you give a value greater than 59, DateTime does check to see that it really matches a valid leap second.
All of the parameters are optional except for "year". The "month" and "day" parameters both default to 1, while the "hour", "minute", "second", and "nanosecond" parameters all default to 0.
The "locale" parameter should be a string matching one of the valid
locales, or a DateTime::Locale
object. See the
DateTime::Locale documentation for details.
The time_zone parameter can be either a scalar or a
DateTime::TimeZone
object. A string will simply be passed to the
DateTime::TimeZone->new
method as its "name" parameter. This
string may be an Olson DB time zone name ("America/Chicago"), an
offset string ("+0630"), or the words "floating" or "local". See the
DateTime::TimeZone
documentation for more details.
The default time zone is "floating".
The "formatter" can be either a scalar or an object, but the class
specified by the scalar or the object must implement a
format_datetime()
method.
This module does not parse dates! That means there is no constructor to which you can pass things like "March 3, 1970 12:34".
Instead, take a look at the various DateTime::Format::*
modules on
CPAN. These parse all sorts of different date formats, and you're
bound to find something that can handle your particular needs.
Because of Daylight Saving Time, it is possible to specify a local time that is ambiguous. For example, in the US in 2003, the transition from to saving to standard time occurred on October 26, at 02:00:00 local time. The local clock changed from 01:59:59 (saving time) to 01:00:00 (standard time). This means that the hour from 01:00:00 through 01:59:59 actually occurs twice, though the UTC time continues to move forward.
If you specify an ambiguous time, then the latest UTC time is always used, in effect always choosing standard time. In this case, you can simply subtract an hour to the object in order to move to saving time, for example:
# This object represent 01:30:00 standard time my $dt = DateTime->new( year => 2003, month => 10, day => 26, hour => 1, minute => 30, second => 0, time_zone => 'America/Chicago', );
print $dt->hms; # prints 01:30:00
# Now the object represent 01:30:00 saving time $dt->subtract( hours => 1 );
print $dt->hms; # still prints 01:30:00
Alternately, you could create the object with the UTC time zone, and
then call the set_time_zone()
method to change the time zone. This
is a good way to ensure that the time is not ambiguous.
Another problem introduced by Daylight Saving Time is that certain local times just do not exist. For example, in the US in 2003, the transition from standard to saving time occurred on April 6, at the change to 2:00:00 local time. The local clock changes from 01:59:59 (standard time) to 03:00:00 (saving time). This means that there is no 02:00:00 through 02:59:59 on April 6!
Attempting to create an invalid time currently causes a fatal error. This may change in future version of this module.
This class method can be used to construct a new DateTime object from
an epoch time instead of components. Just as with the new()
method, it accepts "time_zone", "locale", and "formatter" parameters.
If the epoch value is not an integer, the part after the decimal will
be converted to nanoseconds. This is done in order to be compatible
with Time::HiRes
. If the floating portion extends past 9 decimal
places, it will be truncated to nine, so that 1.1234567891 will become
1 second and 123,456,789 nanoseconds.
By default, the returned object will be in the UTC time zone.
This class method is equivalent to calling from_epoch()
with the
value returned from Perl's time()
function. Just as with the
new()
method, it accepts "time_zone" and "locale" parameters.
By default, the returned object will be in the UTC time zone.
This class method is equivalent to:
DateTime->now(@_)->truncate( to => 'day' );
This class method can be used to construct a new DateTime object from
any object that implements the utc_rd_values()
method. All
DateTime::Calendar
modules must implement this method in order to
provide cross-calendar compatibility. This method accepts a
"locale" and "formatter" parameter
If the object passed to this method has a time_zone()
method, that
is used to set the time zone of the newly created DateTime.pm
object.
Otherwise, the returned object will be in the floating time zone.
This constructor takes the same arguments as can be given to the
new()
method, except for "day". Additionally, both "year" and
"month" are required.
This constructor takes the same arguments as can be given to the
new()
method, except that it does not accept a "month" or "day"
argument. Instead, it requires both "year" and "day_of_year". The
day of year must be between 1 and 366, and 366 is only allowed for
leap years.
clone()
This object method returns a new object that is replica of the object upon which the method is called.
This class has many methods for retrieving information about an object.
year()
Returns the year.
ce_year()
Returns the year according to the BCE/CE numbering system. The year before year 1 in this system is year -1, aka "1 BCE".
era_name()
Returns the long name of the current era, something like "Before Christ". See the Locales section for more details.
era_abbr()
Returns the abbreviated name of the current era, something like "BC". See the Locales section for more details.
christian_era()
Returns a string, either "BC" or "AD", according to the year.
secular_era()
Returns a string, either "BCE" or "CE", according to the year.
year_with_era()
Returns a string containing the year immediately followed by its era
abbreviation. The year is the absolute value of ce_year()
, so that
year 1 is "1AD" and year 0 is "1BC".
year_with_christian_era()
Like year_with_era()
, but uses the christian_era()
method to get the era
name.
year_with_secular_era()
Like year_with_era()
, but uses the secular_era()
method to get the
era name.
month()
Returns the month of the year, from 1..12.
Also available as $dt->mon()
.
month_name()
Returns the name of the current month. See the Locales section for more details.
month_abbr()
Returns the abbreviated name of the current month. See the Locales section for more details.
day()
Returns the day of the month, from 1..31.
Also available as $dt->mday()
and $dt->day_of_month()
.
day_of_week()
Returns the day of the week as a number, from 1..7, with 1 being Monday and 7 being Sunday.
Also available as $dt->wday()
and $dt->dow()
.
local_day_of_week()
Returns the day of the week as a number, from 1..7. The day corresponding to 1 will vary based on the locale.
day_name()
Returns the name of the current day of the week. See the Locales section for more details.
day_abbr()
Returns the abbreviated name of the current day of the week. See the Locales section for more details.
day_of_year()
Returns the day of the year.
Also available as $dt->doy()
.
quarter()
Returns the quarter of the year, from 1..4.
quarter_name()
Returns the name of the current quarter. See the Locales section for more details.
quarter_abbr()
Returns the abbreviated name of the current quarter. See the Locales section for more details.
day_of_quarter()
Returns the day of the quarter.
Also available as $dt->doq()
.
weekday_of_month()
Returns a number from 1..5 indicating which week day of the month this is. For example, June 9, 2003 is the second Monday of the month, and so this method returns 2 for that day.
Each method returns the year, month, and day, in the order indicated by the method name. Years are zero-padded to four digits. Months and days are 0-padded to two digits.
By default, the values are separated by a dash (-), but this can be overridden by passing a value to the method.
The $dt->ymd()
method is also available as $dt->date()
.
hour()
Returns the hour of the day, from 0..23.
Returns the hour of the day, from 1..24.
Returns the hour of the day, from 1..12.
Returns the hour of the day, from 0..11.
am_or_pm()
Returns the appropriate localized abbreviation, depending on the current hour.
minute()
Returns the minute of the hour, from 0..59.
Also available as $dt->min()
.
second()
Returns the second, from 0..61. The values 60 and 61 are used for leap seconds.
Also available as $dt->sec()
.
fractional_second()
Returns the second, as a real number from 0.0 until 61.999999999
The values 60 and 61 are used for leap seconds.
millisecond()
Returns the fractional part of the second as milliseconds (1E-3 seconds).
Half a second is 500 milliseconds.
This value will always be rounded down to the nearest integer.
microsecond()
Returns the fractional part of the second as microseconds (1E-6 seconds).
Half a second is 500_000 microseconds.
This value will always be rounded down to the nearest integer.
nanosecond()
Returns the fractional part of the second as nanoseconds (1E-9 seconds).
Half a second is 500_000_000 nanoseconds.
Returns the hour, minute, and second, all zero-padded to two digits. If no separator is specified, a colon (:) is used by default.
Also available as $dt->time()
.
datetime()
This method is equivalent to:
$dt->ymd('-') . 'T' . $dt->hms(':')
This method is also available as $dt->iso8601()
, but it's not really a
very good ISO8601 format, as it lacks a time zone.
is_leap_year()
This method returns a true or false indicating whether or not the datetime object is in a leap year.
week()
($week_year, $week_number) = $dt->week;
Returns information about the calendar week which contains this datetime object. The values returned by this method are also available separately through the week_year and week_number methods.
The first week of the year is defined by ISO as the one which contains the fourth day of January, which is equivalent to saying that it's the first week to overlap the new year by at least four days.
Typically the week year will be the same as the year that the object is in, but dates at the very beginning of a calendar year often end up in the last week of the prior year, and similarly, the final few days of the year may be placed in the first week of the next year.
week_year()
Returns the year of the week. See $dt->week()
for details.
week_number()
Returns the week of the year, from 1..53. See $dt->week()
for details.
week_of_month()
The week of the month, from 0..5. The first week of the month is the first week that contains a Thursday. This is based on the ICU definition of week of month, and correlates to the ISO8601 week of year definition. A day in the week before the week with the first Thursday will be week 0.
jd()
, $dt->mjd()
These return the Julian Day and Modified Julian Day, respectively. The value returned is a floating point number. The fractional portion of the number represents the time portion of the datetime.
time_zone()
This returns the DateTime::TimeZone
object for the datetime object.
offset()
This returns the offset from UTC, in seconds, of the datetime object according to the time zone.
is_dst()
Returns a boolean indicating whether or not the datetime object is currently in Daylight Saving Time or not.
time_zone_long_name()
This is a shortcut for $dt->time_zone->name
. It's provided so
that one can use "%{time_zone_long_name}" as a strftime format
specifier.
time_zone_short_name()
This method returns the time zone abbreviation for the current time zone, such as "PST" or "GMT". These names are not definitive, and should not be used in any application intended for general use by users around the world.
This method implements functionality similar to the strftime()
method in C. However, if given multiple format strings, then it will
return multiple scalars, one for each format string.
See the strftime Patterns section for a list of all possible strftime patterns.
If you give a pattern that doesn't exist, then it is simply treated as text.
This method implements formatting based on the CLDR date patterns. If given multiple format strings, then it will return multiple scalars, one for each format string.
See the CLDR Patterns section for a list of all possible CLDR patterns.
If you give a pattern that doesn't exist, then it is simply treated as text.
epoch()
Return the UTC epoch value for the datetime object. Internally, this
is implemented using Time::Local
, which uses the Unix epoch even on
machines with a different epoch (such as MacOS). Datetimes before the
start of the epoch will be returned as a negative number.
The return value from this method is always an integer.
Since the epoch does not account for leap seconds, the epoch time for 1972-12-31T23:59:60 (UTC) is exactly the same as that for 1973-01-01T00:00:00.
This module uses Time::Local
to calculate the epoch, which may or
may not handle epochs before 1904 or after 2038 (depending on the size
of your system's integers, and whether or not Perl was compiled with
64-bit int support).
hires_epoch()
Returns the epoch as a floating point number. The floating point
portion of the value represents the nanosecond value of the object.
This method is provided for compatibility with the Time::HiRes
module.
Note that this method suffers from the imprecision of floating point numbers, and the result may end up rounded to an arbitrary degree depending on your platform.
my $dt = DateTime->new( year => 2012, nanosecond => 4 ); say $dt->hires_epoch();
On my system, this simply prints<PHONE_NUMBER>
because adding 0.000000004
to<PHONE_NUMBER>
returns<PHONE_NUMBER>
.
is_finite()
, $dt->is_infinite()
These methods allow you to distinguish normal datetime objects from infinite ones. Infinite datetime objects are documented in DateTime::Infinite.
utc_rd_values()
Returns the current UTC Rata Die days, seconds, and nanoseconds as a three element list. This exists primarily to allow other calendar modules to create objects based on the values provided by this object.
local_rd_values()
Returns the current local Rata Die days, seconds, and nanoseconds as a
three element list. This exists for the benefit of other modules
which might want to use this information for date math, such as
DateTime::Event::Recurrence
.
leap_seconds()
Returns the number of leap seconds that have happened up to the datetime represented by the object. For floating datetimes, this always returns 0.
utc_rd_as_seconds()
Returns the current UTC Rata Die days and seconds purely as seconds. This number ignores any fractional seconds stored in the object, as well as leap seconds.
locale()
Returns the current locale object.
formatter()
Returns current formatter object or class. See Formatters And Stringification for details.
The remaining methods provided by DateTime.pm
, except where otherwise
specified, return the object itself, thus making method chaining
possible. For example:
my $dt = DateTime->now->set_time_zone( 'Australia/Sydney' );
my $first = DateTime ->last_day_of_month( year => 2003, month => 3 ) ->add( days => 1 ) ->subtract( seconds => 1 );
This method can be used to change the local components of a date time,
or its locale. This method accepts any parameter allowed by the
new()
method except for "time_zone". Time zones may be set using
the set_time_zone()
method.
This method performs parameters validation just as is done in the
new()
method.
Do not use this method to do date math. Use the add()
and subtract()
methods instead.
set_year()
, $dt->set_month()
, etc.DateTime has a set_*
method for every item that can be passed to the
constructor:
set_year()
set_month()
set_day()
set_hour()
set_minute()
set_second()
set_nanosecond()
set_locale()
These are shortcuts to calling set()
with a single key. They all
take a single parameter.
This method allows you to reset some of the local time components in the object to their "zero" values. The "to" parameter is used to specify which values to truncate, and it may be one of "year", "month", "week", "local_week" "day", "hour", "minute", or "second". For example, if "month" is specified, then the local day becomes 1, and the hour, minute, and second all become 0.
If "week" is given, then the datetime is set to the Monday of the week in
which it occurs, and the time components are all set to 0. If you truncate to
"local_week", then the first day of the week is locale-dependent. For example,
in the en_US
locale, the first day of the week is Sunday.
This method accepts either a time zone object or a string that can be
passed as the "name" parameter to DateTime::TimeZone->new()
.
If the new time zone's offset is different from the old time zone,
then the local time is adjusted accordingly.
For example:
my $dt = DateTime->new( year => 2000, month => 5, day => 10, hour => 15, minute => 15, time_zone => 'America/Los_Angeles', );
print $dt->hour; # prints 15
$dt->set_time_zone( 'America/Chicago' );
print $dt->hour; # prints 17
If the old time zone was a floating time zone, then no adjustments to the local time are made, except to account for leap seconds. If the new time zone is floating, then the UTC time is adjusted in order to leave the local time untouched.
Fans of Tsai Ming-Liang's films will be happy to know that this does work:
my $dt = DateTime->now( time_zone => 'Asia/Taipei' );
$dt->set_time_zone( 'Europe/Paris' );
Yes, now we can know "ni3 na4 bian1 ji2dian3?"
Set the formatter for the object. See Formatters And Stringification for details.
You can set this to undef
to revert to the default formatter.
Like the set methods, math related methods always return the object itself, to allow for chaining:
$dt->add( days => 1 )->subtract( seconds => 1 );
duration_class()
This returns DateTime::Duration
, but exists so that a subclass of
DateTime.pm
can provide a different value.
This method adds a DateTime::Duration
to the current datetime. See
the DateTime::Duration docs for more details.
This method is syntactic sugar around the add_duration()
method. It
simply creates a new DateTime::Duration
object using the parameters
given, and then calls the add_duration()
method.
When given a DateTime::Duration
object, this method simply calls
invert()
on that object and passes that new duration to the
add_duration
method.
Like add()
, this is syntactic sugar for the subtract_duration()
method.
This method returns a new DateTime::Duration
object representing
the difference between the two dates. The duration is relative to
the object from which $datetime
is subtracted. For example:
2003-03-15 00:00:00.00000000 - 2003-02-15 00:00:00.00000000 ------------------------------- = 1 month
Note that this duration is not an absolute measure of the amount of time between the two datetimes, because the length of a month varies, as well as due to the presence of leap seconds.
The returned duration may have deltas for months, days, minutes, seconds, and nanoseconds.
Each of these methods returns a new DateTime::Duration
object
representing some portion of the difference between two datetimes.
The delta_md()
method returns a duration which contains only the
month and day portions of the duration is represented. The
delta_days()
method returns a duration which contains only days.
The delta_md
and delta_days
methods truncate the duration so
that any fractional portion of a day is ignored. Both of these
methods operate on the date portion of a datetime only, and so
effectively ignore the time zone.
Unlike the subtraction methods, these methods always return a positive (or zero) duration.
Returns a duration which contains only minutes and seconds. Any day and month differences to minutes are converted to minutes and seconds. This method also always return a positive (or zero) duration.
This method returns a new DateTime::Duration
object representing
the difference between the two dates in seconds and nanoseconds. This
is the only way to accurately measure the absolute amount of time
between two datetimes, since units larger than a second do not
represent a fixed number of seconds.
Note that because of leap seconds, this may not return the same result as
doing this math based on the value returned by $dt->epoch()
.
This can be used to specify the default locale to be used when creating DateTime objects. If unset, then "en_US" is used.
$cmp = DateTime->compare( $dt1, $dt2 );
$cmp = DateTime->compare_ignore_floating( $dt1, $dt2 );
Compare two DateTime objects. The semantics are compatible with Perl's
sort()
function; it returns -1 if $dt1 < $dt2, 0 if $dt1 == $dt2, 1 if $dt1
> $dt2.
If one of the two DateTime objects has a floating time zone, it will first be converted to the time zone of the other object. This is what you want most of the time, but it can lead to inconsistent results when you compare a number of DateTime objects, some of which are floating, and some of which are in other time zones.
If you want to have consistent results (because you want to sort a
number of objects, for example), you can use the
compare_ignore_floating()
method:
@dates = sort { DateTime->compare_ignore_floating($a, $b) } @dates;
In this case, objects with a floating time zone will be sorted as if they were UTC times.
Since DateTime objects overload comparison operators, this:
@dates = sort @dates;
is equivalent to this:
@dates = sort { DateTime->compare($a, $b) } @dates;
DateTime objects can be compared to any other calendar class that
implements the utc_rd_values()
method.
If you are trying to test code that calls uses DateTime, you may want to be
able to explicitly set the value returned by Perl's time()
builtin. This
builtin is called by DateTime->now()
and DateTime->today()
.
You can override CORE::GLOBAL::time()
, but this will only work if you do
this before loading DateTime. If doing this is inconvenient, you can also
override DateTime::_core_time()
:
no warnings 'redefine'; local *DateTime::_core_time = sub { return 42 };
DateTime is guaranteed to core this subroutine to get the current time()
value. You can also override the _core_time()
sub in a subclass of DateTime
and use that.
It's important to have some understanding of how datetime math is
implemented in order to effectively use this module and
DateTime::Duration
.
If you want to simplify your life and not have to think too hard about the nitty-gritty of datetime math, I have several recommendations:
If you do not care about time zones or leap seconds, use the "floating" timezone:
my $dt = DateTime->now( time_zone => 'floating' );
Math done on two objects in the floating time zone produces very predictable results.
Note that in most cases you will want to start by creating an object in a specific zone and then convert it to the floating time zone. When an object goes from a real zone to the floating zone, the time for the object remains the same.
This means that passing the floating zone to a constructor may not do what you want.
my $dt = DateTime->now( time_zone => 'floating' );
is equivalent to
my $dt = DateTime->now( time_zone => 'UTC' )->set_time_zone('floating');
This might not be what you wanted. Instead, you may prefer to do this:
my $dt = DateTime->now( time_zone => 'local' )->set_time_zone('floating');
If you do care about time zones (particularly DST) or leap seconds, try to use non-UTC time zones for presentation and user input only. Convert to UTC immediately and convert back to the local time zone for presentation:
my $dt = DateTime->new( %user_input, time_zone => $user_tz ); $dt->set_time_zone('UTC');
# do various operations - store it, retrieve it, add, subtract, etc.
$dt->set_time_zone($user_tz); print $dt->datetime;
If you need to do date math on objects with non-UTC time zones, please
read the caveats below carefully. The results DateTime.pm
produces are
predictable and correct, and mostly intuitive, but datetime math gets
very ugly when time zones are involved, and there are a few strange
corner cases involving subtraction of two datetimes across a DST
change.
If you can always use the floating or UTC time zones, you can skip ahead to Leap Seconds and Date Math
If you only care about the date (calendar) portion of a datetime, you
should use either delta_md()
or delta_days()
, not
subtract_datetime()
. This will give predictable, unsurprising
results, free from DST-related complications.
subtract_datetime()
and add_duration()
You must convert your datetime objects to the UTC time zone before doing date math if you want to make sure that the following formulas are always true:
$dt2 - $dt1 = $dur $dt1 + $dur = $dt2 $dt2 - $dur = $dt1
Note that using delta_days
ensures that this formula always works,
regardless of the timezone of the objects involved, as does using
subtract_datetime_absolute()
. Other methods of subtraction are not
always reversible.
The parts of a duration can be broken down into five parts. These are months, days, minutes, seconds, and nanoseconds. Adding one month to a date is different than adding 4 weeks or 28, 29, 30, or 31 days. Similarly, due to DST and leap seconds, adding a day can be different than adding 86,400 seconds, and adding a minute is not exactly the same as 60 seconds.
We cannot convert between these units, except for seconds and nanoseconds, because there is no fixed conversion between the two units, because of things like leap seconds, DST changes, etc.
DateTime.pm
always adds (or subtracts) days, then months, minutes, and then
seconds and nanoseconds. If there are any boundary overflows, these are
normalized at each step. For the days and months the local (not UTC) values
are used. For minutes and seconds, the local values are used. This generally
just works.
This means that adding one month and one day to February 28, 2003 will produce the date April 1, 2003, not March 29, 2003.
my $dt = DateTime->new( year => 2003, month => 2, day => 28 );
$dt->add( months => 1, days => 1 );
# 2003-04-01 - the result
On the other hand, if we add months first, and then separately add days, we end up with March 29, 2003:
$dt->add( months => 1 )->add( days => 1 );
# 2003-03-29
We see similar strangeness when math crosses a DST boundary:
my $dt = DateTime->new( year => 2003, month => 4, day => 5, hour => 1, minute => 58, time_zone => "America/Chicago", );
$dt->add( days => 1, minutes => 3 ); # 2003-04-06 02:01:00
$dt->add( minutes => 3 )->add( days => 1 ); # 2003-04-06 03:01:00
Note that if you converted the datetime object to UTC first you would get predictable results.
If you want to know how many seconds a duration object represents, you have to add it to a datetime to find out, so you could do:
my $now = DateTime->now( time_zone => 'UTC' ); my $later = $now->clone->add_duration($duration);
my $seconds_dur = $later->subtract_datetime_absolute($now);
This returns a duration which only contains seconds and nanoseconds.
If we were add the duration to a different datetime object we might get a different number of seconds.
the DateTime::Duration manpage supports three different end-of-month algorithms for adding months. This comes into play when an addition results in a day past the end of the month (for example, adding one month to January 30).
# 2010-08-31 + 1 month = 2010-10-01 $dt->add( months => 1, end_of_month => 'wrap' );
# 2010-01-30 + 1 month = 2010-02-28 $dt->add( months => 1, end_of_month => 'limit' );
# 2010-04-30 + 1 month = 2010-05-31 $dt->add( months => 1, end_of_month => 'preserve' );
By default, it uses "wrap" for positive durations and "preserve" for negative durations. See the DateTime::Duration manpage for a detailed explanation of these algorithms.
If you need to do lots of work with durations, take a look at Rick
Measham's DateTime::Format::Duration
module, which lets you present
information from durations in many useful ways.
There are other subtract/delta methods in DateTime.pm to generate
different types of durations. These methods are
subtract_datetime()
, subtract_datetime_absolute()
,
delta_md()
, delta_days()
, and delta_ms()
.
Date subtraction is done solely based on the two object's local datetimes, with one exception to handle DST changes. Also, if the two datetime objects are in different time zones, one of them is converted to the other's time zone first before subtraction. This is best explained through examples:
The first of these probably makes the most sense:
my $dt1 = DateTime->new( year => 2003, month => 5, day => 6, time_zone => 'America/Chicago', );
# not DST
my $dt2 = DateTime->new( year => 2003, month => 11, day => 6, time_zone => 'America/Chicago', );
# is DST
my $dur = $dt2->subtract_datetime($dt1); # 6 months
Nice and simple.
This one is a little trickier, but still fairly logical:
my $dt1 = DateTime->new( year => 2003, month => 4, day => 5, hour => 1, minute => 58, time_zone => "America/Chicago", );
# is DST
my $dt2 = DateTime->new( year => 2003, month => 4, day => 7, hour => 2, minute => 1, time_zone => "America/Chicago", );
# not DST
my $dur = $dt2->subtract_datetime($dt1);
# 2 days and 3 minutes
Which contradicts the result this one gives, even though they both make sense:
my $dt1 = DateTime->new( year => 2003, month => 4, day => 5, hour => 1, minute => 58, time_zone => "America/Chicago", );
# is DST
my $dt2 = DateTime->new( year => 2003, month => 4, day => 6, hour => 3, minute => 1, time_zone => "America/Chicago", );
# not DST
my $dur = $dt2->subtract_datetime($dt1);
# 1 day and 3 minutes
This last example illustrates the "DST" exception mentioned earlier. The exception accounts for the fact 2003-04-06 only lasts 23 hours.
And finally:
my $dt2 = DateTime->new( year => 2003, month => 10, day => 26, hour => 1, time_zone => 'America/Chicago', );
my $dt1 = $dt2->clone->subtract( hours => 1 );
my $dur = $dt2->subtract_datetime($dt1); # 60 minutes
This seems obvious until you realize that subtracting 60 minutes from
$dt2
in the above example still leaves the clock time at
"01:00:00". This time we are accounting for a 25 hour day.
Date math operations are not always reversible. This is because of
the way that addition operations are ordered. As was discussed
earlier, adding 1 day and 3 minutes in one call to add()
is not the
same as first adding 3 minutes and 1 day in two separate calls.
If we take a duration returned from subtract_datetime()
and then
try to add or subtract that duration from one of the datetimes we just
used, we sometimes get interesting results:
my $dt1 = DateTime->new( year => 2003, month => 4, day => 5, hour => 1, minute => 58, time_zone => "America/Chicago", );
my $dt2 = DateTime->new( year => 2003, month => 4, day => 6, hour => 3, minute => 1, time_zone => "America/Chicago", );
my $dur = $dt2->subtract_datetime($dt1); # 1 day and 3 minutes
$dt1->add_duration($dur); # gives us $dt2
$dt2->subtract_duration($dur); # gives us 2003-04-05 02:58:00 - 1 hour later than $dt1
The subtract_duration()
operation gives us a (perhaps) unexpected
answer because it first subtracts one day to get 2003-04-05T03:01:00
and then subtracts 3 minutes to get the final result.
If we explicitly reverse the order we can get the original value of
$dt1
. This can be facilitated by DateTime::Duration
's
calendar_duration()
and clock_duration()
methods:
$dt2->subtract_duration( $dur->clock_duration ) ->subtract_duration( $dur->calendar_duration );
The presence of leap seconds can cause even more anomalies in date math. For example, the following is a legal datetime:
my $dt = DateTime->new( year => 1972, month => 12, day => 31, hour => 23, minute => 59, second => 60, time_zone => 'UTC' );
If we do the following:
$dt->add( months => 1 );
Then the datetime is now "1973-02-01 00:00:00", because there is no 23:59:60 on 1973-01-31.
Leap seconds also force us to distinguish between minutes and seconds during date math. Given the following datetime:
my $dt = DateTime->new( year => 1972, month => 12, day => 31, hour => 23, minute => 59, second => 30, time_zone => 'UTC' );
we will get different results when adding 1 minute than we get if we add 60 seconds. This is because in this case, the last minute of the day, beginning at 23:59:00, actually contains 61 seconds.
Here are the results we get:
# 1972-12-31 23:59:30 - our starting datetime
$dt->clone->add( minutes => 1 ); # 1973-01-01 00:00:30 - one minute later
$dt->clone->add( seconds => 60 ); # 1973-01-01 00:00:29 - 60 seconds later
$dt->clone->add( seconds => 61 ); # 1973-01-01 00:00:30 - 61 seconds later
When math crosses a daylight saving boundary, a single day may have more or less than 24 hours.
For example, if you do this:
my $dt = DateTime->new( year => 2003, month => 4, day => 5, hour => 2, time_zone => 'America/Chicago', );
$dt->add( days => 1 );
then you will produce an invalid local time, and therefore an exception will be thrown.
However, this works:
my $dt = DateTime->new( year => 2003, month => 4, day => 5, hour => 2, time_zone => 'America/Chicago', );
$dt->add( hours => 24 );
and produces a datetime with the local time of "03:00".
If all this makes your head hurt, there is a simple alternative. Just convert your datetime object to the "UTC" time zone before doing date math on it, and switch it back to the local time zone afterwards. This avoids the possibility of having date math throw an exception, and makes sure that 1 day equals 24 hours. Of course, this may not always be desirable, so caveat user!
This module explicitly overloads the addition (+), subtraction (-), string and numeric comparison operators. This means that the following all do sensible things:
my $new_dt = $dt + $duration_obj;
my $new_dt = $dt - $duration_obj;
my $duration_obj = $dt - $new_dt;
foreach my $dt ( sort @dts ) { ... }
Additionally, the fallback parameter is set to true, so other derivable operators (+=, -=, etc.) will work properly. Do not expect increment (++) or decrement (--) to do anything useful.
The string comparison operators, eq
or ne
, will use the string
value to compare with non-DateTime objects.
DateTime objects do not have a numeric value, using ==
or <=>
to compare a DateTime object with a non-DateTime object will result
in an exception. To safely sort mixed DateTime and non-DateTime
objects, use sort { $a cmp $b } @dates
.
The module also overloads stringification using the object's
formatter, defaulting to iso8601()
method. See Formatters And Stringification for details.
You can optionally specify a "formatter", which is usually a DateTime::Format::* object/class, to control the stringification of the DateTime object.
Any of the constructor methods can accept a formatter argument:
my $formatter = DateTime::Format::Strptime->new(...); my $dt = DateTime->new(year => 2004, formatter => $formatter);
Or, you can set it afterwards:
$dt->set_formatter($formatter); $formatter = $dt->formatter();
Once you set the formatter, the overloaded stringification method will
use the formatter. If unspecified, the iso8601()
method is used.
A formatter can be handy when you know that in your application you want to stringify your DateTime objects into a special format all the time, for example to a different language.
If you provide a formatter class name or object, it must implement a
format_datetime
method. This method will be called with just the
DateTime object as its argument.
The CLDR pattern language is both more powerful and more complex than strftime. Unlike strftime patterns, you often have to explicitly escape text that you do not want formatted, as the patterns are simply letters without any prefix.
For example, "yyyy-MM-dd" is a valid CLDR pattern. If you want to include any lower or upper case ASCII characters as-is, you can surround them with single quotes ('). If you want to include a single quote, you must escape it as two single quotes ('').
'Today is ' EEEE 'It is now' h 'o''clock' a
Spaces and any non-letter text will always be passed through as-is.
Many CLDR patterns which produce numbers will pad the number with leading zeroes depending on the length of the format specifier. For example, "h" represents the current hour from 1-12. If you specify "hh" then the 1-9 will have a leading zero prepended.
However, CLDR often uses five of a letter to represent the narrow form of a pattern. This inconsistency is necessary for backwards compatibility.
CLDR often distinguishes between the "format" and "stand-alone" forms of a pattern. The format pattern is used when the thing in question is being placed into a larger string. The stand-alone form is used when displaying that item by itself, for example in a calendar.
It also often provides three sizes for each item, wide (the full name), abbreviated, and narrow. The narrow form is often just a single character, for example "T" for "Tuesday", and may not be unique.
CLDR provides a fairly complex system for localizing time zones that
we ignore entirely. The time zone patterns just use the information
provided by DateTime::TimeZone
, and do not follow the CLDR spec.
The output of a CLDR pattern is always localized, when applicable.
CLDR provides the following patterns:
The abbreviated era (BC, AD).
The wide era (Before Christ, Anno Domini).
The narrow era, if it exists (and it mostly doesn't).
The year, zero-prefixed as needed. Negative years will start with a "-", and this will be included in the length calculation.
In other, words the "yyyyy" pattern will format year -1234 as "-1234", not "-01234".
This is a special case. It always produces a two-digit year, so "1976" becomes "76". Negative years will start with a "-", making them one character longer.
The year in "week of the year" calendars, from $dt->week_year()
.
Same as "y" except that "uu" is not a special case.
The quarter as a number (1..4).
The abbreviated format form for the quarter.
The wide format form for the quarter.
The quarter as a number (1..4).
The abbreviated stand-alone form for the quarter.
The wide stand-alone form for the quarter.
The numerical month.
The abbreviated format form for the month.
The wide format form for the month.
The narrow format form for the month.
The numerical month.
The abbreviated stand-alone form for the month.
The wide stand-alone form for the month.
The narrow stand-alone form for the month.
The week of the year, from $dt->week_number()
.
The week of the month, from $dt->week_of_month()
.
The numeric day of the month.
The numeric day of the year.
The day of the week in the month, from $dt->weekday_of_month()
.
The modified Julian day, from $dt->mjd()
.
The abbreviated format form for the day of the week.
The wide format form for the day of the week.
The narrow format form for the day of the week.
The local numeric day of the week, from 1 to 7. This number depends on what day is considered the first day of the week, which varies by locale. For example, in the US, Sunday is the first day of the week, so this returns 2 for Monday.
The numeric day of the week from 1 to 7, treating Monday as the first of the week, regardless of locale.
The abbreviated stand-alone form for the day of the week.
The wide stand-alone form for the day of the week.
The narrow format form for the day of the week.
The localized form of AM or PM for the time.
The hour from 1-12.
The hour from 0-23.
The hour from 0-11.
The hour from 1-24.
The hour, in 12 or 24 hour form, based on the preferred form for the locale. In other words, this is equivalent to either "h{1,2}" or "H{1,2}".
The minute.
The second.
The fractional portion of the seconds, rounded based on the length of the specifier. This returned without a leading decimal point, but may have leading or trailing zeroes.
The millisecond of the day, based on the current time. In other words, if it is 12:00:00.00, this returns 43200000.
The time zone short name.
The time zone long name.
The time zone offset.
The time zone short name and the offset as one string, so something like "CDT-0500".
The time zone offset as a sexagesimal number, so something like "-05:00". (This is useful for W3C format.)
The time zone short name.
The time zone long name.
The time zone short name.
The time zone long name.
The following patterns are allowed in the format string given to the
$dt->strftime()
method:
The abbreviated weekday name.
The full weekday name.
The abbreviated month name.
The full month name.
The default datetime format for the object's locale.
The century number (year/100) as a 2-digit integer.
The day of the month as a decimal number (range 01 to 31).
Equivalent to %m/%d/%y. This is not a good standard format if you want folks from both the United States and the rest of the world to understand the date!
Like %d, the day of the month as a decimal number, but a leading zero is replaced by a space.
Equivalent to %Y-%m-%d (the ISO 8601 date format)
The ISO 8601 year with century as a decimal number. The 4-digit year corresponding to the ISO week number (see %V). This has the same format and value as %Y, except that if the ISO week number belongs to the previous or next year, that year is used instead. (TZ)
Like %G, but without century, i.e., with a 2-digit year (00-99).
Equivalent to %b.
The hour as a decimal number using a 24-hour clock (range 00 to 23).
The hour as a decimal number using a 12-hour clock (range 01 to 12).
The day of the year as a decimal number (range 001 to 366).
The hour (24-hour clock) as a decimal number (range 0 to 23); single digits are preceded by a blank. (See also %H.)
The hour (12-hour clock) as a decimal number (range 1 to 12); single digits are preceded by a blank. (See also %I.)
The month as a decimal number (range 01 to 12).
The minute as a decimal number (range 00 to 59).
A newline character.
The fractional seconds digits. Default is 9 digits (nanoseconds).
%3N milliseconds (3 digits) %6N microseconds (6 digits) %9N nanoseconds (9 digits)
This value will always be rounded down to the nearest integer.
Either `AM' or `PM' according to the given time value, or the corresponding strings for the current locale. Noon is treated as `pm' and midnight as `am'.
Like %p but in lowercase: `am' or `pm' or a corresponding string for the current locale.
The time in a.m. or p.m. notation. In the POSIX locale this is equivalent to `%I:%M:%S %p'.
The time in 24-hour notation (%H:%M). (SU) For a version including the seconds, see %T below.
The number of seconds since the epoch.
The second as a decimal number (range 00 to 61).
A tab character.
The time in 24-hour notation (%H:%M:%S).
The day of the week as a decimal, range 1 to 7, Monday being 1. See also %w.
The week number of the current year as a decimal number, range 00 to 53, starting with the first Sunday as the first day of week 01. See also %V and %W.
The ISO 8601:1988 week number of the current year as a decimal number, range 01 to 53, where week 1 is the first week that has at least 4 days in the current year, and with Monday as the first day of the week. See also %U and %W.
The day of the week as a decimal, range 0 to 6, Sunday being 0. See also %u.
The week number of the current year as a decimal number, range 00 to 53, starting with the first Monday as the first day of week 01.
The default date format for the object's locale.
The default time format for the object's locale.
The year as a decimal number without a century (range 00 to 99).
The year as a decimal number including the century.
The time-zone as hour offset from UTC. Required to emit RFC822-conformant dates (using "%a, %d %b %Y %H:%M:%S %z").
The time zone or name or abbreviation.
A literal `%' character.
Any method name may be specified using the format %{method}
name
where "method" is a valid DateTime.pm
object method.
DateTime implements Storable hooks in order to reduce the size of a serialized DateTime object.
This module is part of a larger ecosystem of modules in the DateTime family.
The the DateTime::Set manpage module represents sets (including recurrences) of datetimes. Many modules return sets or recurrences.
The various format modules exist to parse and format datetimes. For example, the DateTime::Format::HTTP manpage parses dates according to the RFC 1123 format:
my $datetime = DateTime::Format::HTTP->parse_datetime('Thu Feb 3 17:03:55 GMT 1994');
print DateTime::Format::HTTP->format_datetime($datetime);
Most format modules are suitable for use as a formatter
with a DateTime
object.
All format modules start with DateTime::Format::
.
There are a number of modules on CPAN that implement non-Gregorian calendars, such as the Chinese, Mayan, and Julian calendars.
All calendar modules start with DateTime::Calendar::
.
There are a number of modules that calculate the dates for events, such as Easter, Sunrise, etc.
All event modules start with DateTime::Event::
.
There are many other modules that work with DateTime, including modules in the
DateTimeX
namespace, as well as others.
See the datetime wiki and search.cpan.org for more details.
The tests in 20infinite.t seem to fail on some machines, particularly on Win32. This appears to be related to Perl's internal handling of IEEE infinity and NaN, and seems to be highly platform/compiler/phase of moon dependent.
If you don't plan to use infinite datetimes you can probably ignore this. This will be fixed (perhaps) in future versions.
Support for this module is provided via the<EMAIL_ADDRESS>email list. See http://datetime.perl.org/wiki/datetime/page/Mailing_List for details.
Please submit bugs to the CPAN RT system at http://rt.cpan.org/NoAuth/Bugs.html?Dist=DateTime or via email at<EMAIL_ADDRESS>If you'd like to thank me for the work I've done on this module, please consider making a "donation" to me via PayPal. I spend a lot of free time creating free software, and would appreciate any support you'd care to offer.
Please note that I am not suggesting that you must do this in order for me to continue working on this particular software. I will continue to do so, inasmuch as I have in the past, for as long as it interests me.
Similarly, a donation made in this way will probably not make me work on this software much more, unless I get so many donations that I can consider working on free software full time, which seems unlikely at best.
To donate, log into PayPal and send money to<EMAIL_ADDRESS>or use the button on this page: http://www.urth.org/~autarch/fs-donation.html
A Date with Perl - a talk I've given at a few YAPCs.
<EMAIL_ADDRESS>mailing list
Dave Rolsky<EMAIL_ADDRESS>Ben Bennett<EMAIL_ADDRESS>Christian Hansen<EMAIL_ADDRESS>Daisuke Maki<EMAIL_ADDRESS>David E. Wheeler<EMAIL_ADDRESS>Doug Bell<EMAIL_ADDRESS>Flávio Soibelmann Glock<EMAIL_ADDRESS>Gregory Oschwald<EMAIL_ADDRESS>Iain Truskett <deceased>
Jason McIntosh<EMAIL_ADDRESS>Joshua Hoblitt<EMAIL_ADDRESS>Ricardo Signes<EMAIL_ADDRESS>Richard Bowen<EMAIL_ADDRESS>Ron Hill<EMAIL_ADDRESS>This software is Copyright (c) 2015 by Dave Rolsky.
This is free software, licensed under:
The Artistic License 2.0 (GPL Compatible)
| DateTime - A date and time object for Perl |